feat: supervise engine worker and gate readiness on READY

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 17:07:23 +02:00
parent 9a7712d1db
commit 8d50331e4d
8 changed files with 194 additions and 20 deletions
+1 -1
View File
@@ -20,4 +20,4 @@ Read `PROJECT_CHARTER.md` before changing architecture, performance policy, or s
## Repository state
The Strata source is present under `engine/strata/` at the commit recorded in `docs/upstream.md`. The Rust control plane currently exposes only health, readiness, and status; inference APIs, project benchmark results, and deployment assets are not yet present. Read `engine/strata/AGENTS.md` before modifying imported engine code.
The Strata source is present under `engine/strata/` at the commit recorded in `docs/upstream.md`. The Rust control plane currently exposes only health, readiness, and status, and can supervise one configured worker; inference APIs, project benchmark results, and deployment assets are not yet present. Read `engine/strata/AGENTS.md` before modifying imported engine code.
+1 -1
View File
@@ -4,7 +4,7 @@ Strata Next is a planned C++20/CUDA inference engine fork with a Rust control pl
## Current state
The Strata source is imported at a pinned upstream commit under `engine/strata/`. A CPU-only source build and unit tests are available through `scripts/build-cpu.sh`. A minimal Rust control plane serves health, readiness, and status; it does not yet start an engine worker or handle inference requests. The project benchmark harness, deployment image, and verified GPU performance baseline have **not** been implemented yet. Figures in the charter are preliminary reference points, not results from this repository.
The Strata source is imported at a pinned upstream commit under `engine/strata/`. A CPU-only source build and unit tests are available through `scripts/build-cpu.sh`. A minimal Rust control plane serves health, readiness, and status and can supervise one engine worker; it does not yet handle inference requests. The project benchmark harness, deployment image, and verified GPU performance baseline have **not** been implemented yet. Figures in the charter are preliminary reference points, not results from this repository.
## Layout
+2
View File
@@ -391,6 +391,7 @@ version = "0.1.0"
dependencies = [
"axum",
"serde",
"serde_json",
"tokio",
]
@@ -417,6 +418,7 @@ version = "1.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
dependencies = [
"bytes",
"libc",
"mio",
"pin-project-lite",
+2 -1
View File
@@ -7,4 +7,5 @@ rust-version = "1.85"
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] }
serde_json = "1"
tokio = { version = "1", features = ["io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] }
+3 -1
View File
@@ -1,5 +1,7 @@
# Control plane
The Rust control plane has its first runnable milestone: process health, worker readiness, status, and graceful shutdown. It does not yet start an engine worker or expose inference API routes. Readiness correctly returns HTTP 503 until a worker is loaded in a later milestone.
The Rust control plane has its first runnable milestone: process health, worker readiness, status, and graceful shutdown. It can start a Strata engine worker and marks readiness only after the engine emits `READY <max-context>`. It does not yet expose inference API routes or restart a failed worker.
Run locally with `cargo run --manifest-path control-plane/Cargo.toml`. It binds to `127.0.0.1:8081` by default; set `STRATA_BIND` to another socket address if needed. Check `/health`, `/ready`, and `/status`.
Set `STRATA_ENGINE_EXE` to the engine executable and `STRATA_ENGINE_ARGS_JSON` to a JSON array of engine arguments to start a worker. The control plane supplies `--serve` itself. Without an engine configuration, `/ready` returns HTTP 503 and `/status` reports `unconfigured`. A configured worker reports `starting`, then `ready` with `max_context`, or `failed` if startup or the process fails.
+29 -16
View File
@@ -1,25 +1,22 @@
mod worker;
use std::{env, net::SocketAddr, sync::Arc};
use axum::{Json, Router, extract::State, http::StatusCode, routing::get};
use serde::Serialize;
use tokio::sync::RwLock;
use tokio::sync::{RwLock, watch};
#[derive(Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
enum WorkerState {
Unconfigured,
Ready,
}
use worker::{WorkerConfig, WorkerState, WorkerStatus};
#[derive(Clone)]
struct AppState {
worker: Arc<RwLock<WorkerState>>,
worker: Arc<RwLock<WorkerStatus>>,
}
impl AppState {
fn new() -> Self {
Self {
worker: Arc::new(RwLock::new(WorkerState::Unconfigured)),
worker: Arc::new(RwLock::new(WorkerStatus::default())),
}
}
}
@@ -35,6 +32,7 @@ struct StatusResponse {
version: &'static str,
worker: WorkerState,
ready: bool,
max_context: Option<usize>,
}
fn router(state: AppState) -> Router {
@@ -51,7 +49,7 @@ async fn health() -> Json<HealthResponse> {
async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
let worker = *state.worker.read().await;
let code = if worker == WorkerState::Ready {
let code = if worker.state == WorkerState::Ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
@@ -63,12 +61,13 @@ async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
Json(status_body(*state.worker.read().await))
}
fn status_body(worker: WorkerState) -> StatusResponse {
fn status_body(worker: WorkerStatus) -> StatusResponse {
StatusResponse {
service: "strata-control",
version: env!("CARGO_PKG_VERSION"),
worker,
ready: worker == WorkerState::Ready,
worker: worker.state,
ready: worker.state == WorkerState::Ready,
max_context: worker.max_context,
}
}
@@ -77,11 +76,25 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let bind: SocketAddr = env::var("STRATA_BIND")
.unwrap_or_else(|_| "127.0.0.1:8081".to_owned())
.parse()?;
let worker_config = WorkerConfig::from_env()?;
let listener = tokio::net::TcpListener::bind(bind).await?;
let state = AppState::new();
let (shutdown_tx, shutdown_rx) = watch::channel(false);
let worker_task = worker_config
.map(|config| tokio::spawn(worker::run(config, state.worker.clone(), shutdown_rx)));
eprintln!("strata-control listening on {}", listener.local_addr()?);
axum::serve(listener, router(AppState::new()))
.with_graceful_shutdown(shutdown_signal())
.await?;
let server_shutdown = shutdown_tx.clone();
let result = axum::serve(listener, router(state))
.with_graceful_shutdown(async move {
shutdown_signal().await;
let _ = server_shutdown.send(true);
})
.await;
let _ = shutdown_tx.send(true);
if let Some(task) = worker_task {
task.await?;
}
result?;
Ok(())
}
+148
View File
@@ -0,0 +1,148 @@
use std::{env, ffi::OsString, process::Stdio, sync::Arc, time::Duration};
use serde::Serialize;
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
process::{Child, ChildStdin, Command},
sync::{RwLock, watch},
time::timeout,
};
#[derive(Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkerState {
Unconfigured,
Starting,
Ready,
Failed,
}
#[derive(Clone, Copy)]
pub struct WorkerStatus {
pub state: WorkerState,
pub max_context: Option<usize>,
}
impl Default for WorkerStatus {
fn default() -> Self {
Self {
state: WorkerState::Unconfigured,
max_context: None,
}
}
}
pub struct WorkerConfig {
executable: OsString,
args: Vec<String>,
}
impl WorkerConfig {
pub fn from_env() -> Result<Option<Self>, Box<dyn std::error::Error>> {
let executable = env::var_os("STRATA_ENGINE_EXE");
let args = env::var("STRATA_ENGINE_ARGS_JSON").ok();
match (executable, args) {
(None, None) => Ok(None),
(None, Some(_)) => Err("STRATA_ENGINE_ARGS_JSON requires STRATA_ENGINE_EXE".into()),
(Some(executable), args) => Ok(Some(Self {
executable,
args: args
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?
.unwrap_or_default(),
})),
}
}
}
pub async fn run(
config: WorkerConfig,
status: Arc<RwLock<WorkerStatus>>,
mut shutdown: watch::Receiver<bool>,
) {
update(&status, WorkerState::Starting, None).await;
let mut child = match Command::new(&config.executable)
.arg("--serve")
.args(&config.args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()
{
Ok(child) => child,
Err(error) => {
eprintln!("failed to start Strata engine: {error}");
update(&status, WorkerState::Failed, None).await;
return;
}
};
// Keep stdin outside Child: Child::wait closes any stdin it still owns.
let mut stdin = child.stdin.take();
let stdout = child.stdout.take().expect("piped engine stdout");
let mut lines = BufReader::new(stdout).lines();
loop {
let line = tokio::select! {
_ = shutdown.changed() => {
stop(&mut child, &mut stdin).await;
return;
}
line = lines.next_line() => line,
};
match line {
Ok(Some(line)) if line.starts_with("READY ") => {
let max_context = line
.split_whitespace()
.nth(1)
.and_then(|s| s.parse::<usize>().ok());
if let Some(max_context) = max_context.filter(|value| *value > 0) {
update(&status, WorkerState::Ready, Some(max_context)).await;
break;
}
eprintln!("Strata engine sent an invalid READY line");
stop(&mut child, &mut stdin).await;
update(&status, WorkerState::Failed, None).await;
return;
}
Ok(Some(_)) => {}
Ok(None) => {
eprintln!("Strata engine exited before READY");
update(&status, WorkerState::Failed, None).await;
return;
}
Err(error) => {
eprintln!("failed to read Strata engine output: {error}");
stop(&mut child, &mut stdin).await;
update(&status, WorkerState::Failed, None).await;
return;
}
}
}
tokio::select! {
_ = shutdown.changed() => stop(&mut child, &mut stdin).await,
result = child.wait() => {
eprintln!("Strata engine exited: {result:?}");
update(&status, WorkerState::Failed, None).await;
}
}
}
async fn update(status: &RwLock<WorkerStatus>, state: WorkerState, max_context: Option<usize>) {
*status.write().await = WorkerStatus { state, max_context };
}
async fn stop(child: &mut Child, stdin: &mut Option<ChildStdin>) {
if let Some(mut pipe) = stdin.take() {
let _ = pipe.write_all(b"QUIT\n").await;
let _ = pipe.flush().await;
}
if timeout(Duration::from_secs(20), child.wait())
.await
.is_err()
{
let _ = child.start_kill();
let _ = child.wait().await;
}
}
+8
View File
@@ -11,3 +11,11 @@
- Scope: source compilation and CPU tests only. No CUDA build, model inference, or performance measurement was performed.
The test toolchain was installed into ignored `artifacts/tool-venv/` for this run; it is not a production dependency.
## 2026-10-02 — Rust control-plane smoke test
- `cargo fmt --check` and `cargo check --locked` passed with Rust 1.95.0.
- With no worker configured: `/health` returned 200 and `/ready` returned 503.
- With an ignored local fake engine that emitted `READY 262144 stop`: `/ready` returned 200 with `max_context: 262144`; Ctrl-C shut down both processes.
- With a fake engine that exited after `READY`: `/ready` returned 503 with `worker: failed`.
- `/v1/responses` is not implemented and returned 404. No model inference was tested.