From 8d50331e4db9539347f722cc1d757b07d1f31229 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 2 Oct 2026 17:07:23 +0200 Subject: [PATCH] feat: supervise engine worker and gate readiness on READY --- AGENTS.md | 2 +- README.md | 2 +- control-plane/Cargo.lock | 2 + control-plane/Cargo.toml | 3 +- control-plane/README.md | 4 +- control-plane/src/main.rs | 45 +++++++---- control-plane/src/worker.rs | 148 ++++++++++++++++++++++++++++++++++++ docs/build-validation.md | 8 ++ 8 files changed, 194 insertions(+), 20 deletions(-) create mode 100644 control-plane/src/worker.rs diff --git a/AGENTS.md b/AGENTS.md index 290e86b6..bbb01807 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/README.md b/README.md index cc059e9e..a57baea8 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/control-plane/Cargo.lock b/control-plane/Cargo.lock index 2385abf7..dcfade7c 100644 --- a/control-plane/Cargo.lock +++ b/control-plane/Cargo.lock @@ -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", diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml index 86d475a3..0ceb95a7 100644 --- a/control-plane/Cargo.toml +++ b/control-plane/Cargo.toml @@ -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"] } diff --git a/control-plane/README.md b/control-plane/README.md index bd39fa00..d5c38f9b 100644 --- a/control-plane/README.md +++ b/control-plane/README.md @@ -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 `. 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. diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 85ebf2cc..6e6d9ad7 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -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>, + worker: Arc>, } 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, } fn router(state: AppState) -> Router { @@ -51,7 +49,7 @@ async fn health() -> Json { async fn ready(State(state): State) -> (StatusCode, Json) { 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) -> Json { 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> { 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(()) } diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs new file mode 100644 index 00000000..5bfd9202 --- /dev/null +++ b/control-plane/src/worker.rs @@ -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, +} + +impl Default for WorkerStatus { + fn default() -> Self { + Self { + state: WorkerState::Unconfigured, + max_context: None, + } + } +} + +pub struct WorkerConfig { + executable: OsString, + args: Vec, +} + +impl WorkerConfig { + pub fn from_env() -> Result, Box> { + 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::>(&value)) + .transpose()? + .unwrap_or_default(), + })), + } + } +} + +pub async fn run( + config: WorkerConfig, + status: Arc>, + mut shutdown: watch::Receiver, +) { + 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::().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, state: WorkerState, max_context: Option) { + *status.write().await = WorkerStatus { state, max_context }; +} + +async fn stop(child: &mut Child, stdin: &mut Option) { + 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; + } +} diff --git a/docs/build-validation.md b/docs/build-validation.md index 81ed2872..1f00aa07 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -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.