Files
leleka/control-plane/src/worker.rs
T

509 lines
17 KiB
Rust

use std::{ffi::OsString, process::Stdio, sync::Arc, time::Duration};
use serde::Serialize;
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
process::{Child, ChildStdin, Command},
sync::{RwLock, mpsc, oneshot, watch},
time::timeout,
};
use crate::wire::{self, Event, Generate};
pub struct GenerationCommand {
pub request: Generate,
pub result: oneshot::Sender<Result<Vec<Event>, String>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkerState {
Unconfigured,
Starting,
Ready,
Stopping,
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 {
pub executable: OsString,
pub args: Vec<String>,
pub startup_timeout: Duration,
}
pub async fn run(
config: WorkerConfig,
status: Arc<RwLock<WorkerStatus>>,
shutdown: watch::Receiver<bool>,
) {
let (sender, receiver) = mpsc::channel(1);
run_with_requests(config, status, shutdown, receiver).await;
drop(sender);
}
pub async fn run_with_requests(
config: WorkerConfig,
status: Arc<RwLock<WorkerStatus>>,
mut shutdown: watch::Receiver<bool>,
mut requests: mpsc::Receiver<GenerationCommand>,
) {
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();
let startup_deadline = tokio::time::sleep(config.startup_timeout);
tokio::pin!(startup_deadline);
let max_context = loop {
let line = tokio::select! {
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
stop(&mut child, &mut stdin).await;
return;
}
_ = &mut startup_deadline => {
eprintln!("Strata engine did not become ready before the startup timeout");
stop(&mut child, &mut stdin).await;
update(&status, WorkerState::Failed, None).await;
return;
}
line = lines.next_line() => line,
};
match line {
Ok(Some(line)) if line.starts_with("READY") => {
if let Some(max_context) = parse_ready(&line) {
update(&status, WorkerState::Ready, Some(max_context)).await;
break max_context;
}
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;
}
}
};
let mut requests_closed = false;
loop {
tokio::select! {
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
stop(&mut child, &mut stdin).await;
return;
},
result = child.wait() => {
eprintln!("Strata engine exited: {result:?}");
update(&status, WorkerState::Failed, None).await;
return;
},
command = requests.recv(), if !requests_closed => {
match command {
Some(command) => {
tokio::select! {
result = generate(&mut stdin, &mut lines, command, max_context) => {
if let Err(error) = result {
eprintln!("Strata engine protocol failed: {error}");
stop(&mut child, &mut stdin).await;
update(&status, WorkerState::Failed, None).await;
return;
}
}
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
stop_active(&mut child, &mut stdin).await;
return;
}
}
}
None => requests_closed = true,
}
}
}
}
}
async fn generate(
stdin: &mut Option<ChildStdin>,
lines: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
mut command: GenerationCommand,
max_context: usize,
) -> Result<(), String> {
if command.result.is_closed() {
return Ok(());
}
let fits_context = usize::try_from(command.request.max_new)
.ok()
.and_then(|new| command.request.token_ids.len().checked_add(new))
.and_then(|total| total.checked_add(8))
.is_some_and(|total| total <= max_context);
if !fits_context {
let _ = command.result.send(Err(
"prompt, output budget, and 8-token margin exceed context".to_owned(),
));
return Ok(());
}
let request = match command.request.line() {
Ok(line) => line,
Err(error) => {
let _ = command.result.send(Err(error.to_owned()));
return Ok(());
}
};
let pipe = stdin.as_mut().ok_or("engine stdin is closed")?;
pipe.write_all(request.as_bytes())
.await
.map_err(|error| error.to_string())?;
pipe.flush().await.map_err(|error| error.to_string())?;
let mut events = Vec::new();
let mut stopped = false;
loop {
let line = tokio::select! {
line = lines.next_line() => line.map_err(|error| error.to_string())?,
_ = command.result.closed(), if !stopped => {
pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?;
pipe.flush().await.map_err(|error| error.to_string())?;
stopped = true;
continue;
}
}
.ok_or("engine exited before a terminal line")?;
match wire::parse_line(&line)? {
Some(Event::Error(message)) => {
let _ = command.result.send(Err(message));
return Ok(());
}
Some(event @ Event::Done(_)) => {
events.push(event);
let _ = command.result.send(Ok(events));
return Ok(());
}
Some(event) => events.push(event),
None => {}
}
}
}
fn parse_ready(line: &str) -> Option<usize> {
let mut fields = line.split_whitespace();
if fields.next() != Some("READY") {
return None;
}
let context = fields.next()?.parse::<usize>().ok()?;
(context > 0).then_some(context)
}
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;
}
}
async fn stop_active(child: &mut Child, stdin: &mut Option<ChildStdin>) {
if let Some(pipe) = stdin.as_mut() {
let _ = pipe.write_all(b"STOP\n").await;
let _ = pipe.flush().await;
}
stop(child, stdin).await;
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::path::Path;
fn fixture_config(mode: &str, timeout_s: u64) -> WorkerConfig {
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/mock_engine.sh")
.into_os_string();
WorkerConfig {
executable: script,
args: vec![mode.to_owned()],
startup_timeout: Duration::from_secs(timeout_s),
}
}
async fn wait_for(status: &RwLock<WorkerStatus>, wanted: WorkerState) {
timeout(Duration::from_secs(5), async {
loop {
if status.read().await.state == wanted {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("worker state transition");
}
#[tokio::test]
async fn ready_requires_handshake_and_shutdown_sends_quit() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let task = tokio::spawn(run(fixture_config("ready", 5), status.clone(), stop_rx));
wait_for(&status, WorkerState::Ready).await;
assert_eq!(status.read().await.max_context, Some(262144));
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
}
#[tokio::test]
async fn worker_exit_revokes_readiness() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
run(fixture_config("crash", 5), status.clone(), stop_rx).await;
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.max_context, None);
}
#[tokio::test]
async fn startup_timeout_never_sets_ready() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
run(fixture_config("slow", 1), status.clone(), stop_rx).await;
assert_eq!(status.read().await.state, WorkerState::Failed);
}
#[test]
fn ready_line_requires_positive_context() {
assert_eq!(parse_ready("READY 262144 stop"), Some(262144));
assert_eq!(parse_ready("READY 0 stop"), None);
assert_eq!(parse_ready("READY nope stop"), None);
}
#[tokio::test]
async fn supervisor_exchanges_one_generation_and_stays_ready() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
fixture_config("exchange", 5),
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: Some(0.5),
top_p: Some(0.9),
},
result: result_tx,
})
.await
.unwrap();
let events = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events.len(), 4);
assert_eq!(events[1], Event::Token(31));
assert_eq!(events[2], Event::Token(32));
assert!(matches!(events[3], Event::Done(_)));
assert_eq!(status.read().await.state, WorkerState::Ready);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![10, 20],
max_new: 300_000,
temperature: None,
top_p: None,
},
result: result_tx,
})
.await
.unwrap();
assert!(
result_rx
.await
.unwrap()
.unwrap_err()
.contains("exceed context")
);
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn dropped_generation_receiver_sends_stop_and_preserves_worker() {
let marker =
std::env::temp_dir().join(format!("strata-cancel-drop-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: result_tx,
})
.await
.unwrap();
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
drop(result_rx);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
},
result: result_tx,
})
.await
.unwrap();
let events = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_file(marker).unwrap();
}
#[tokio::test]
async fn shutdown_interrupts_active_generation() {
let marker =
std::env::temp_dir().join(format!("strata-cancel-shutdown-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: result_tx,
})
.await
.unwrap();
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
assert!(result_rx.await.is_err());
std::fs::remove_file(marker).unwrap();
}
}