[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

+8
View File
@@ -0,0 +1,8 @@
[package]
name = "vetta-infer-kn"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
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
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Fence-guarded `SlabRing` DMA ownership state machine.
//!
//! Directly implements the transitions verified in `proofs/slab_ring_dma.lean`:
//! `Free -> IoInFlight -> GpuReady -> GpuInUse -> Free`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotState {
Free,
IoInFlight { req_id: u64 },
GpuReady { tag: u64 },
GpuInUse { tag: u64, fence: u64 },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SlabError {
OutOfBounds { idx: usize, cap: usize },
InvalidTransition { idx: usize, state: SlotState, op: &'static str },
TagMismatch { idx: usize, expected: u64, actual: u64 },
FenceMismatch { idx: usize, expected: u64, actual: u64 },
NoFreeSlot,
}
impl std::fmt::Display for SlabError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for SlabError {}
/// Tracks ownership of `N` page-aligned zero-copy UMA buffers shared between `io_uring` and HIP.
#[derive(Debug, Clone)]
pub struct SlabRing {
slots: Vec<SlotState>,
slot_bytes: usize,
}
impl SlabRing {
pub fn new(num_slots: usize, slot_bytes: usize) -> Self {
assert!(num_slots > 0, "SlabRing requires at least 1 slot");
Self {
slots: vec![SlotState::Free; num_slots],
slot_bytes,
}
}
pub fn len(&self) -> usize {
self.slots.len()
}
pub fn is_empty(&self) -> bool {
self.slots.is_empty()
}
pub fn slot_bytes(&self) -> usize {
self.slot_bytes
}
pub fn state(&self, idx: usize) -> Result<SlotState, SlabError> {
self.slots
.get(idx)
.copied()
.ok_or(SlabError::OutOfBounds { idx, cap: self.slots.len() })
}
pub fn find_free(&self) -> Option<usize> {
self.slots.iter().position(|&s| s == SlotState::Free)
}
pub fn submit_io(&mut self, idx: usize, req_id: u64) -> Result<(), SlabError> {
let s = self.state(idx)?;
if s != SlotState::Free {
return Err(SlabError::InvalidTransition { idx, state: s, op: "submit_io" });
}
self.slots[idx] = SlotState::IoInFlight { req_id };
Ok(())
}
pub fn complete_io(&mut self, idx: usize, req_id: u64, tag: u64) -> Result<(), SlabError> {
match self.state(idx)? {
SlotState::IoInFlight { req_id: cur } if cur == req_id => {
self.slots[idx] = SlotState::GpuReady { tag };
Ok(())
}
other => Err(SlabError::InvalidTransition { idx, state: other, op: "complete_io" }),
}
}
pub fn abort_io(&mut self, idx: usize, req_id: u64) -> Result<(), SlabError> {
match self.state(idx)? {
SlotState::IoInFlight { req_id: cur } if cur == req_id => {
self.slots[idx] = SlotState::Free;
Ok(())
}
other => Err(SlabError::InvalidTransition { idx, state: other, op: "abort_io" }),
}
}
pub fn launch_gpu(&mut self, idx: usize, expected_tag: u64, fence: u64) -> Result<(), SlabError> {
match self.state(idx)? {
SlotState::GpuReady { tag } if tag == expected_tag => {
self.slots[idx] = SlotState::GpuInUse { tag, fence };
Ok(())
}
SlotState::GpuReady { tag } => {
Err(SlabError::TagMismatch { idx, expected: expected_tag, actual: tag })
}
other => Err(SlabError::InvalidTransition { idx, state: other, op: "launch_gpu" }),
}
}
pub fn discard_ready(&mut self, idx: usize) -> Result<(), SlabError> {
match self.state(idx)? {
SlotState::GpuReady { .. } => {
self.slots[idx] = SlotState::Free;
Ok(())
}
other => Err(SlabError::InvalidTransition { idx, state: other, op: "discard_ready" }),
}
}
pub fn complete_gpu(&mut self, idx: usize, fence: u64) -> Result<(), SlabError> {
match self.state(idx)? {
SlotState::GpuInUse { fence: cur, .. } if cur == fence => {
self.slots[idx] = SlotState::Free;
Ok(())
}
SlotState::GpuInUse { fence: cur, .. } => {
Err(SlabError::FenceMismatch { idx, expected: cur, actual: fence })
}
other => Err(SlabError::InvalidTransition { idx, state: other, op: "complete_gpu" }),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn full_ping_pong_lifecycle_and_safety() {
let mut ring = SlabRing::new(3, 4 * 1024 * 1024);
let s0 = ring.find_free().unwrap();
assert_eq!(s0, 0);
// Cannot launch GPU before DMA completes
assert!(ring.launch_gpu(s0, 10, 1).is_err());
ring.submit_io(s0, 100).unwrap();
// Cannot launch GPU while IO is still in flight
assert!(ring.launch_gpu(s0, 10, 1).is_err());
ring.complete_io(s0, 100, 10).unwrap();
// Cannot overwrite with new IO while GpuReady or GpuInUse
assert!(ring.submit_io(s0, 101).is_err());
ring.launch_gpu(s0, 10, 42).unwrap();
assert!(ring.submit_io(s0, 102).is_err());
assert!(ring.complete_gpu(s0, 999).is_err()); // wrong fence rejected
ring.complete_gpu(s0, 42).unwrap();
assert_eq!(ring.state(s0).unwrap(), SlotState::Free);
}
}
+94
View File
@@ -0,0 +1,94 @@
//! UMA slab pool — the broker's buffer ownership surface.
//!
//! 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 crate::slab::{SlabError, SlabRing, SlotState};
/// Page-aligned host/UMA ring backing `SlabRing` transitions.
pub struct UmaSlabPool {
ring: SlabRing,
buffers: Vec<Vec<u8>>,
next_req_id: u64,
next_fence_id: u64,
}
impl UmaSlabPool {
pub fn new(num_slots: usize, slot_bytes: usize) -> Self {
let mut buffers = Vec::with_capacity(num_slots);
for _ in 0..num_slots {
buffers.push(vec![0u8; slot_bytes]);
}
Self {
ring: SlabRing::new(num_slots, slot_bytes),
buffers,
next_req_id: 1,
next_fence_id: 1,
}
}
pub fn slot_state(&self, idx: usize) -> Result<SlotState, SlabError> {
self.ring.state(idx)
}
/// Acquires a free slot and enters `IoInFlight`, returning `(slot_idx, req_id, &mut [u8])`.
/// No GPU kernel can read this slot until `complete_io` transitions it to `GpuReady`.
pub fn begin_io(&mut self) -> Result<(usize, u64, &mut [u8]), SlabError> {
let idx = self.ring.find_free().ok_or(SlabError::NoFreeSlot)?;
let req_id = self.next_req_id;
self.next_req_id += 1;
self.ring.submit_io(idx, req_id)?;
Ok((idx, req_id, self.buffers[idx].as_mut_slice()))
}
pub fn complete_io(&mut self, idx: usize, req_id: u64, tag: u64) -> Result<(), SlabError> {
self.ring.complete_io(idx, req_id, tag)
}
pub fn abort_io(&mut self, idx: usize, req_id: u64) -> Result<(), SlabError> {
self.ring.abort_io(idx, req_id)
}
/// Transitions a `GpuReady` slot to `GpuInUse` and returns `(fence_id, &[u8])`.
/// The slot cannot be reused for DMA until `complete_gpu(idx, fence_id)` is called.
pub fn launch_gpu(&mut self, idx: usize, expected_tag: u64) -> Result<(u64, &[u8]), SlabError> {
let fence = self.next_fence_id;
self.next_fence_id += 1;
self.ring.launch_gpu(idx, expected_tag, fence)?;
Ok((fence, self.buffers[idx].as_slice()))
}
pub fn complete_gpu(&mut self, idx: usize, fence: u64) -> Result<(), SlabError> {
self.ring.complete_gpu(idx, fence)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uma_slab_pool_enforces_dma_gpu_exclusion() {
let mut pool = UmaSlabPool::new(2, 4096);
let (s0, req0, buf0) = pool.begin_io().unwrap();
buf0[0] = 0xAB;
// Cannot launch GPU before IO completes
assert!(pool.launch_gpu(s0, 77).is_err());
pool.complete_io(s0, req0, 77).unwrap();
let (fence, ro) = pool.launch_gpu(s0, 77).unwrap();
assert_eq!(ro[0], 0xAB);
// Slot 0 is GpuInUse so begin_io must hand out Slot 1
let (s1, req1, _) = pool.begin_io().unwrap();
assert_eq!(s1, 1);
// Pool is now full (s0=GpuInUse, s1=IoInFlight)
assert_eq!(pool.begin_io().unwrap_err(), SlabError::NoFreeSlot);
pool.complete_gpu(s0, fence).unwrap();
assert_eq!(pool.slot_state(s0).unwrap(), SlotState::Free);
pool.abort_io(s1, req1).unwrap();
assert_eq!(pool.slot_state(s1).unwrap(), SlotState::Free);
}
}