Files
vetta-infer/crates/vetta-infer-gw/src/session.rs
T
adm 7b50f1c07c [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.
2026-11-30 00:54:00 +01:00

263 lines
8.9 KiB
Rust

//! `--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);
}
}