Files
strata-ctl/src/engine/supervisor.rs
T
adm 597ac432e1 strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API)
From-scratch rewrite of the Python serve (Python kept as behavioral spec).

- engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog,
  abort, is_idle probe.
- config: tolerant shared-JSON loader; foreign keys ignored so one file drives
  strata-ctl and uostream; CLI --config/--host/--port/--serve.
- inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template
  via minijinja; channel-token dialect (reasoning streamed live); image bridge
  (in-process Vision, image=<path>); formatter assembling the API seam.
- api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health;
  reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side
  execution); stop sequences with hold-back; abort on client disconnect.

69 tests green + 2 real-file ignored; clippy clean. Text, images and tools
validated live against the real Inkling engine.
2026-11-24 05:28:56 +01:00

342 lines
12 KiB
Rust

//! Supervisor of the resident `strata --serve` child process.
//!
//! The engine speaks a line protocol on stdin/stdout (see [`super::protocol`]).
//! This module owns the process: start, one request at a time (the Python
//! layer serializes requests on a FIFO too — a `--parallel 1` engine has one
//! control stream and one conversation cache), STOP-then-drain when a request
//! ends early, and a clean QUIT on shutdown.
use std::collections::BTreeMap;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command;
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::sync::Mutex;
use super::protocol::{gen_line, Done, EngineLine, LineKind, Sampling};
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
#[error("failed to spawn the engine: {0}")]
Spawn(std::io::Error),
#[error("the engine did not become ready: {0}")]
Startup(String),
#[error("the engine stopped unexpectedly")]
Died,
#[error("the engine refused the request: {0}")]
Refused(String),
#[error("the engine produced no output for {0:?}")]
Silent(Duration),
}
/// What the engine advertised on its `READY` line.
#[derive(Debug, Clone, Copy)]
pub struct Ready {
pub max_context: u32,
pub can_stop: bool,
pub can_hold: bool,
pub can_hold_batch: bool,
}
/// Everything one request collected from the engine's answer.
#[derive(Debug, Default)]
pub struct Outcome {
/// The generated token ids, in order.
pub tokens: Vec<u32>,
/// The engine's figures from its `DONE` line.
pub done: Option<Done>,
/// Prompt tokens served from the conversation cache (`RESUME`).
pub resumed: u32,
}
/// A running engine plus the mutex that keeps one request on the wires at a
/// time. Cheap to share: wrap in `Arc` and every HTTP handler contends on it.
pub struct Engine {
pipes: Mutex<Guarded>,
/// The in-flight request's cancel flag and a second handle on stdin, so
/// `abort` works while a request holds the lock (Python's `cancel` event
/// and the STOP write from another thread).
ctl: Abort,
ready: Ready,
info: Mutex<BTreeMap<String, String>>,
silence: Duration,
}
struct Abort {
flag: std::sync::atomic::AtomicBool,
stdin: tokio::sync::Mutex<ChildStdin>,
}
/// The child and its pipes, handed to whoever holds the request lock.
struct Guarded {
child: Child,
stdout: BufReader<ChildStdout>,
dead: bool,
}
impl Engine {
/// Spawns `<exe> <args...>` (the supervisor is generic: the config layer
/// builds the full argv, e.g. `["--serve", "--native", model, ...]` for the
/// real engine) and waits, up to `ready_timeout`, for the `READY` line,
/// logging the startup `INFO` facts on the way.
pub async fn start(
exe: &str,
args: &[String],
cwd: Option<&str>,
ready_timeout: Duration,
) -> Result<Self, EngineError> {
let mut cmd = Command::new(exe);
cmd.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.kill_on_drop(true);
if let Some(cwd) = cwd {
cmd.current_dir(cwd);
}
let mut child = cmd.spawn().map_err(EngineError::Spawn)?;
let stdin = child.stdin.take().expect("stdin piped");
let stdout = BufReader::new(child.stdout.take().expect("stdout piped"));
let mut guarded = Guarded {
child,
stdout,
dead: false,
};
let ctl = Abort {
flag: std::sync::atomic::AtomicBool::new(false),
stdin: Mutex::new(stdin),
};
// Everything before READY is startup chatter; a protocol line that is
// neither READY nor INFO means the engine refused to start (bad model
// path, no VRAM, ...): surface it instead of timing out.
let mut unexpected: Vec<String> = Vec::new();
let mut startup_info: BTreeMap<String, String> = BTreeMap::new();
let ready = match tokio::time::timeout(ready_timeout, async {
loop {
let line = match read_line(&mut guarded.stdout).await {
Ok(l) => l,
Err(e) => return Err(e),
};
match EngineLine::parse(&line) {
EngineLine::Ready {
max_context,
can_stop,
can_hold,
can_hold_batch,
} => {
return Ok(Ready {
max_context,
can_stop,
can_hold,
can_hold_batch,
})
}
EngineLine::Info(kv) => {
startup_info.extend(kv);
}
EngineLine::Err(msg) => {
return Err(EngineError::Startup(format!(
"the engine refused to start: {msg}"
)))
}
_ => unexpected.push(line.trim().to_string()),
}
}
})
.await
{
Err(_) => {
return Err(EngineError::Startup(format!(
"timed out waiting for READY (saw: {unexpected:?})"
)))
}
Ok(r) => r,
}?;
for (k, v) in &startup_info {
tracing::info!(key = %k, value = %v, "engine info");
}
Ok(Self {
pipes: Mutex::new(guarded),
ctl,
ready,
info: Mutex::new(startup_info),
silence: Duration::from_secs(600),
})
}
pub fn ready(&self) -> Ready {
self.ready
}
pub async fn info(&self) -> BTreeMap<String, String> {
self.info.lock().await.clone()
}
/// Runs one generation to completion, forwarding each engine line to
/// `on_event` as it arrives. Returns when the engine prints `DONE`, or on
/// refusal/death. Requests queue on the engine's lock — like the Python
/// service's FIFO — since one engine has one control stream and one
/// conversation cache.
pub async fn generate<F>(
&self,
max_new: u32,
sampling: &Sampling,
ids: &[u32],
mut on_event: F,
) -> Result<Outcome, EngineError>
where
F: FnMut(&EngineLine),
{
let mut g = self.pipes.lock().await;
if g.dead {
return Err(EngineError::Died);
}
let line = gen_line(max_new, sampling, ids);
self.ctl
.flag
.store(false, std::sync::atomic::Ordering::Relaxed);
if let Err(e) = self.send(&line).await {
g.dead = true;
return Err(e);
}
let mut out = Outcome::default();
loop {
// `abort` (client gone, caller gave up) only needs to set the flag
// and reach the engine's stdin: the DONE it triggers is drained
// here, inside the request that owns the wires.
if self.ctl.flag.load(std::sync::atomic::Ordering::Relaxed) {
self.send("STOP\n").await?;
drain_to_done(&mut g.stdout).await?;
return Err(EngineError::Refused("aborted".into()));
}
let raw = match tokio::time::timeout(self.silence, read_line(&mut g.stdout)).await {
Err(_) => {
// Computing a huge prompt or hung, we cannot tell: stop it
// and report, like Python's silence watchdog. The DONE we
// trigger is drained here, so the wires stay usable.
let _ = self.send("STOP\n").await;
let _ = drain_to_done(&mut g.stdout).await;
return Err(EngineError::Silent(self.silence));
}
Ok(Err(e)) => {
g.dead = true;
return Err(e);
}
Ok(Ok(raw)) => raw,
};
let parsed = EngineLine::parse(&raw);
match &parsed {
EngineLine::Token(id) => out.tokens.push(*id),
EngineLine::Resume(n) => out.resumed = *n,
EngineLine::Info(kv) => {
self.info.lock().await.extend(kv.clone());
}
EngineLine::Done(done) => {
out.done = Some(done.clone());
on_event(&parsed);
return Ok(out);
}
EngineLine::Err(msg) => {
// An engine that ends a request on ERR may still print its
// DONE: swallow it, or the next request would read it as
// its own (serve/server.py `_swallow_trailing_done`).
swallow_trailing_done(&mut g.stdout).await;
return Err(EngineError::Refused(msg.clone()));
}
_ => {}
}
on_event(&parsed);
}
}
/// Writes one command to the engine's stdin (shared with `abort`, which
/// may run while a request holds the read lock).
async fn send(&self, line: &str) -> Result<(), EngineError> {
let mut stdin = self.ctl.stdin.lock().await;
write(&mut stdin, line).await
}
/// Signals the in-flight request to stop (like Python's `cancel` event):
/// sets the flag and pokes the engine with STOP. The request's own future
/// drains to DONE, so this returns promptly even while a request holds the
/// wires. `Ok(false)` when nothing is running to abort.
pub async fn abort(&self) -> Result<bool, EngineError> {
// If we can grab the read lock, no request owns the wires: nothing to
// abort. Otherwise flag the running request (it drains) and send STOP.
if self.pipes.try_lock().is_ok() {
return Ok(false);
}
self.ctl
.flag
.store(true, std::sync::atomic::Ordering::Relaxed);
self.send("STOP\n").await?;
Ok(true)
}
/// True when no request owns the wires (non-mutating probe, unlike abort).
pub fn is_idle(&self) -> bool {
self.pipes.try_lock().is_ok()
}
/// `QUIT` and reap the child.
pub async fn shutdown(&self) -> Result<(), EngineError> {
let mut g = self.pipes.lock().await;
if g.dead {
return Ok(());
}
let _ = self.send("QUIT\n").await;
let _ = tokio::time::timeout(Duration::from_secs(5), g.child.wait()).await;
let _ = g.child.start_kill();
g.dead = true;
Ok(())
}
}
async fn drain_to_done(stdout: &mut BufReader<ChildStdout>) -> Result<(), EngineError> {
loop {
match EngineLine::parse(&read_line(stdout).await?).into_kind() {
LineKind::Done | LineKind::Err => return Ok(()),
_ => continue,
}
}
}
async fn swallow_trailing_done(stdout: &mut BufReader<ChildStdout>) {
for _ in 0..4 {
let Ok(Ok(raw)) = tokio::time::timeout(Duration::from_millis(300), read_line(stdout)).await
else {
return;
};
match EngineLine::parse(&raw).into_kind() {
LineKind::Done | LineKind::Err => return,
_ => continue,
}
}
}
async fn write(stdin: &mut ChildStdin, line: &str) -> Result<(), EngineError> {
stdin
.write_all(line.as_bytes())
.await
.map_err(|_| EngineError::Died)?;
stdin.flush().await.map_err(|_| EngineError::Died)
}
/// Reads one line; EOF (the engine exited) is [`EngineError::Died`].
async fn read_line(stdout: &mut BufReader<ChildStdout>) -> Result<String, EngineError> {
let mut line = String::new();
let n = stdout
.read_line(&mut line)
.await
.map_err(|_| EngineError::Died)?;
if n == 0 {
return Err(EngineError::Died);
}
Ok(line)
}