Files
leleka/control-plane/src/worker.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

1273 lines
45 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};
const STOP_DRAIN_TIMEOUT: Duration = Duration::from_secs(20);
pub struct GenerationCommand {
pub queue: Option<crate::queue::Ticket>,
pub activity: Option<crate::lifecycle::Guard>,
pub request: Generate,
pub result: GenerationResult,
}
pub enum GenerationResult {
Buffered(oneshot::Sender<Result<Vec<Event>, String>>),
Streaming(mpsc::Sender<Result<Event, String>>),
Finished,
}
impl GenerationResult {
fn take(&mut self) -> Self {
std::mem::replace(self, Self::Finished)
}
fn is_closed(&self) -> bool {
match self {
Self::Buffered(sender) => sender.is_closed(),
Self::Streaming(sender) => sender.is_closed(),
Self::Finished => true,
}
}
async fn closed(&mut self) {
match self {
Self::Buffered(sender) => sender.closed().await,
Self::Streaming(sender) => sender.closed().await,
Self::Finished => {}
}
}
async fn send_event(&self, event: Event) {
if let Self::Streaming(sender) = self {
let _ = sender.send(Ok(event)).await;
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkerState {
Unconfigured,
Starting,
Restarting,
Ready,
Stopping,
Failed,
}
#[derive(Clone, Copy)]
pub struct WorkerStatus {
pub state: WorkerState,
pub max_context: Option<usize>,
pub metrics: crate::metrics::GenerationMetrics,
}
impl Default for WorkerStatus {
fn default() -> Self {
Self {
state: WorkerState::Unconfigured,
max_context: None,
metrics: Default::default(),
}
}
}
pub struct WorkerConfig {
pub cuda_memory: Option<crate::cuda_memory::Selection>,
pub executable: OsString,
pub args: Vec<String>,
pub startup_timeout: Duration,
pub generation_timeout: Option<Duration>,
pub max_restarts: u32,
}
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>,
) {
if config.max_restarts > 3 {
eprintln!("worker max_restarts must be between 0 and 3");
update(&status, WorkerState::Failed, None).await;
return;
}
for attempt in 0..=config.max_restarts {
match run_session(&config, &status, &mut shutdown, &mut requests).await {
SessionExit::Stopped | SessionExit::StartupFailed => return,
SessionExit::RuntimeFailed if attempt == config.max_restarts => return,
SessionExit::RuntimeFailed => {}
}
update(&status, WorkerState::Restarting, None).await;
let delay = Duration::from_secs(2 << attempt);
eprintln!(
"Strata engine restart {}/{} in {} seconds",
attempt + 1,
config.max_restarts,
delay.as_secs()
);
while let Ok(command) = requests.try_recv() {
send_failure(
command.result,
"worker failed; request was not replayed".to_owned(),
)
.await;
}
let backoff = tokio::time::sleep(delay);
tokio::pin!(backoff);
let mut requests_closed = requests.is_closed() && requests.is_empty();
loop {
tokio::select! {
biased;
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
return;
}
_ = &mut backoff => break,
command = requests.recv(), if !requests_closed => {
match command {
Some(command) => send_failure(command.result,
"worker is restarting; request was not replayed".to_owned()).await,
None => requests_closed = true,
}
}
}
}
}
}
enum SessionExit {
Stopped,
StartupFailed,
RuntimeFailed,
}
async fn run_session(
config: &WorkerConfig,
status: &RwLock<WorkerStatus>,
shutdown: &mut watch::Receiver<bool>,
requests: &mut mpsc::Receiver<GenerationCommand>,
) -> SessionExit {
if *shutdown.borrow() {
update(status, WorkerState::Stopping, None).await;
return SessionExit::Stopped;
}
update(status, WorkerState::Starting, None).await;
let mut command = Command::new(&config.executable);
if let Some(selection) = &config.cuda_memory {
if let Err(error) = selection.recheck().await {
eprintln!("GPU admission failed before worker spawn: {error}");
update(status, WorkerState::Failed, None).await;
return SessionExit::StartupFailed;
}
command.env("CUDA_VISIBLE_DEVICES", &selection.uuid);
}
if *shutdown.borrow() {
update(status, WorkerState::Stopping, None).await;
return SessionExit::Stopped;
}
let mut child = match command
.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 SessionExit::StartupFailed;
}
};
// 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 mut requests_closed = false;
let max_context = loop {
let line = tokio::select! {
biased;
_ = shutdown.changed() => {
update(status, WorkerState::Stopping, None).await;
stop(&mut child, &mut stdin).await;
return SessionExit::Stopped;
}
_ = &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 SessionExit::StartupFailed;
}
command = requests.recv(), if !requests_closed => {
match command {
Some(command) => send_failure(command.result,
"worker is starting; request was not replayed".to_owned()).await,
None => requests_closed = true,
}
continue;
}
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 SessionExit::StartupFailed;
}
Ok(Some(_)) => {}
Ok(None) => {
eprintln!("Strata engine exited before READY");
terminate(&mut child, &mut stdin).await;
update(status, WorkerState::Failed, None).await;
return SessionExit::StartupFailed;
}
Err(error) => {
eprintln!("failed to read Strata engine output: {error}");
stop(&mut child, &mut stdin).await;
update(status, WorkerState::Failed, None).await;
return SessionExit::StartupFailed;
}
}
};
loop {
tokio::select! {
_ = shutdown.changed() => {
update(status, WorkerState::Stopping, None).await;
stop(&mut child, &mut stdin).await;
return SessionExit::Stopped;
},
result = child.wait() => {
eprintln!("Strata engine exited: {result:?}");
update(status, WorkerState::Failed, None).await;
return SessionExit::RuntimeFailed;
},
command = requests.recv(), if !requests_closed => {
match command {
Some(mut command) => {
if command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim()) {
continue;
}
// Retain the command activity until protocol cleanup,
// including STOP/QUIT and failed-process termination.
let _activity = command.activity.take();
tokio::select! {
(timed_out, result) = async {
let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status);
match config.generation_timeout {
Some(duration) => match timeout(duration, generation).await {
Ok(result) => (false, result),
Err(_) => (true, Err("generation exceeded configured execution deadline".to_owned())),
},
None => (false, generation.await),
}
} => {
if let Err(error) = result {
eprintln!("Strata engine protocol failed: {error}");
update(status, WorkerState::Failed, None).await;
terminate(&mut child, &mut stdin).await;
// A full streaming channel must not delay process cleanup
// or finite restart indefinitely. Closing it also signals
// failure to the response adapter once buffered tokens drain.
if timed_out {
let _ = timeout(Duration::from_secs(1), send_failure(command.result, error)).await;
}
return SessionExit::RuntimeFailed;
}
}
_ = shutdown.changed() => {
update(status, WorkerState::Stopping, None).await;
stop_active(&mut child, &mut stdin).await;
return SessionExit::Stopped;
}
}
}
None => requests_closed = true,
}
}
}
}
}
async fn generate(
stdin: &mut Option<ChildStdin>,
lines: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
command: &mut GenerationCommand,
max_context: usize,
status: &RwLock<WorkerStatus>,
) -> 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 {
send_failure(
command.result.take(),
"prompt, output budget, and 8-token margin exceed context".to_owned(),
)
.await;
return Ok(());
}
let request = match command.request.line() {
Ok(line) => line,
Err(error) => {
send_failure(command.result.take(), error.to_owned()).await;
return Ok(());
}
};
status.write().await.metrics.start();
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;
let stop_deadline = tokio::time::sleep(STOP_DRAIN_TIMEOUT);
tokio::pin!(stop_deadline);
loop {
let line = tokio::select! {
biased;
_ = &mut stop_deadline, if stopped => {
return Err("engine did not terminate generation within 20 seconds of STOP".to_owned());
}
_ = 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;
stop_deadline.as_mut().reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT);
continue;
}
line = lines.next_line() => line.map_err(|error| error.to_string())?,
}
.ok_or("engine exited before a terminal line")?;
match wire::parse_line(&line)? {
Some(Event::Error(message)) => {
status.write().await.metrics.fail();
send_failure(command.result.take(), message).await;
return Ok(());
}
Some(event @ Event::Done(_)) => {
let Event::Done(done) = &event else {
unreachable!()
};
let done = done.clone();
let disconnected = stopped || command.result.is_closed();
match command.result.take() {
GenerationResult::Buffered(sender) => {
events.push(event);
let _ = sender.send(Ok(events));
}
GenerationResult::Streaming(sender) => {
let _ = sender.send(Ok(event)).await;
}
GenerationResult::Finished => {}
}
status.write().await.metrics.finish(&done, disconnected);
return Ok(());
}
Some(_) if stopped => {}
Some(event) => match &command.result {
GenerationResult::Buffered(_) => events.push(event),
GenerationResult::Streaming(_) => command.result.send_event(event).await,
GenerationResult::Finished => {}
},
None => {}
}
}
}
async fn send_failure(result: GenerationResult, message: String) {
match result {
GenerationResult::Buffered(sender) => {
let _ = sender.send(Err(message));
}
GenerationResult::Streaming(sender) => {
let _ = sender.send(Err(message)).await;
}
GenerationResult::Finished => {}
}
}
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>) {
let mut status = status.write().await;
if state != WorkerState::Ready {
status.metrics.fail();
}
status.state = state;
status.max_context = 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;
}
// Protocol alignment is lost: never reuse this process or add another graceful
// wait after an expired STOP deadline. Dropping the request receiver releases
// queued clients when the supervisor returns.
async fn terminate(child: &mut Child, stdin: &mut Option<ChildStdin>) {
stdin.take();
let _ = child.start_kill();
let _ = child.wait().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 {
cuda_memory: None,
executable: script,
args: vec![mode.to_owned()],
startup_timeout: Duration::from_secs(timeout_s),
generation_timeout: None,
max_restarts: 0,
}
}
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 execution_deadline_covers_blocked_engine_stdin() {
let mut config = fixture_config("blocked-input", 5);
config.generation_timeout = Some(Duration::from_millis(100));
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
requests_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result, received) = oneshot::channel();
requests
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10000; 200000],
max_new: 1,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(result),
})
.await
.unwrap();
let error = timeout(Duration::from_secs(5), received)
.await
.unwrap()
.unwrap()
.unwrap_err();
assert_eq!(error, "generation exceeded configured execution deadline");
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.metrics.failed_or_interrupted, 1);
}
#[tokio::test]
async fn execution_deadline_covers_full_stream_channel_and_releases_activity() {
let mut config = fixture_config("flood", 5);
config.generation_timeout = Some(Duration::from_millis(100));
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(2);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
requests_rx,
));
wait_for(&status, WorkerState::Ready).await;
let lifecycle = crate::lifecycle::Lifecycle::default();
let (events, mut received) = mpsc::channel(1);
requests
.send(GenerationCommand {
queue: None,
activity: Some(lifecycle.generation()),
request: Generate {
token_ids: vec![10],
max_new: 100,
temperature: None,
top_p: None,
},
result: GenerationResult::Streaming(events),
})
.await
.unwrap();
// Do not read until the worker exits: channel backpressure must not mask timeout.
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.metrics.failed_or_interrupted, 1);
assert_eq!(status.read().await.metrics.completed, 0);
assert_eq!(lifecycle.snapshot().generation_jobs, 0);
assert!(matches!(received.recv().await, Some(Ok(Event::Token(31)))));
assert!(received.recv().await.is_none());
}
#[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 {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: Some(0.5),
top_p: Some(0.9),
},
result: GenerationResult::Buffered(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(_)));
let metrics = status.read().await.metrics;
assert_eq!(metrics.started, 1);
assert_eq!(metrics.completed, 1);
assert_eq!(metrics.done_generated_tokens, 2);
assert_eq!(metrics.done_prompt_tokens, 2);
assert_eq!(
metrics.last_done.unwrap().decode_tokens_per_second,
Some(1000.0)
);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 300_000,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
assert!(
result_rx
.await
.unwrap()
.unwrap_err()
.contains("exceed context")
);
assert_eq!(status.read().await.metrics.started, 1);
let (invalid, result) = command(vec![99], 1);
commands_tx.send(invalid).await.unwrap();
assert_eq!(result.await.unwrap().unwrap_err(), "unexpected request");
let metrics = status.read().await.metrics;
assert_eq!(
(
metrics.started,
metrics.completed,
metrics.failed_or_interrupted
),
(2, 1, 1)
);
assert!(metrics.active_since.is_none());
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 {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
assert!(status.read().await.metrics.active_since.is_some());
drop(result_rx);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
let events = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(metrics.started, metrics.completed, metrics.cancelled),
(2, 1, 1)
);
assert_eq!(metrics.failed_or_interrupted, 0);
assert!(metrics.active_since.is_none());
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 dropped_stream_receiver_stops_generation_and_preserves_worker() {
let marker =
std::env::temp_dir().join(format!("strata-stream-cancel-{}", std::process::id()));
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 (events_tx, mut events_rx) = mpsc::channel(2);
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: GenerationResult::Streaming(events_tx),
})
.await
.unwrap();
assert_eq!(
timeout(Duration::from_secs(5), events_rx.recv())
.await
.unwrap()
.unwrap()
.unwrap(),
Event::Token(31)
);
drop(events_rx);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
let next = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(next[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(metrics.started, metrics.completed, metrics.cancelled),
(2, 1, 1)
);
assert_eq!(metrics.failed_or_interrupted, 0);
assert!(metrics.active_since.is_none());
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 {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(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());
let metrics = status.read().await.metrics;
assert_eq!(metrics.failed_or_interrupted, 1);
assert!(metrics.active_since.is_none());
std::fs::remove_file(marker).unwrap();
}
#[tokio::test]
async fn uncooperative_stop_revokes_readiness_and_releases_queued_request() {
let marker =
std::env::temp_dir().join(format!("strata-stalled-cancel-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel-stall", 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 (events_tx, mut events_rx) = mpsc::channel(1);
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: GenerationResult::Streaming(events_tx),
})
.await
.unwrap();
assert_eq!(
timeout(Duration::from_secs(5), events_rx.recv())
.await
.unwrap()
.unwrap()
.unwrap(),
Event::Token(31)
);
let cancel_at = tokio::time::Instant::now();
drop(events_rx);
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(result_tx),
})
.await
.unwrap();
timeout(STOP_DRAIN_TIMEOUT + Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert!(cancel_at.elapsed() >= STOP_DRAIN_TIMEOUT);
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.max_context, None);
assert!(
result_rx.await.is_err(),
"must not reuse the unaligned worker"
);
assert!(commands_tx.is_closed());
drop(stop_tx);
std::fs::remove_file(marker).unwrap();
}
fn restart_fixture(
mode: &str,
label: &str,
max_restarts: u32,
) -> (WorkerConfig, std::path::PathBuf) {
let root =
std::env::temp_dir().join(format!("strata-restart-{label}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir(&root).unwrap();
let mut config = fixture_config(mode, 5);
config.max_restarts = max_restarts;
config.args.push(root.display().to_string());
(config, root)
}
fn command(
token_ids: Vec<u32>,
max_new: u32,
) -> (
GenerationCommand,
oneshot::Receiver<Result<Vec<Event>, String>>,
) {
let (sender, receiver) = oneshot::channel();
(
GenerationCommand {
queue: None,
activity: None,
request: Generate {
token_ids,
max_new,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(sender),
},
receiver,
)
}
#[tokio::test]
async fn crash_restarts_worker_without_replaying_active_or_queued_requests() {
let (config, root) = restart_fixture("restart-once", "once", 1);
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 (first, failed) = command(vec![10, 20], 3);
commands_tx.send(first).await.unwrap();
timeout(Duration::from_secs(5), async {
while !root.join("active").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let (queued, rejected) = command(vec![99], 1);
commands_tx.send(queued).await.unwrap();
std::fs::write(root.join("release"), "").unwrap();
assert!(
timeout(Duration::from_secs(5), failed)
.await
.unwrap()
.is_err()
);
assert!(
timeout(Duration::from_secs(5), rejected)
.await
.unwrap()
.unwrap()
.unwrap_err()
.contains("not replayed")
);
wait_for(&status, WorkerState::Restarting).await;
let (during_backoff, rejected) = command(vec![99], 1);
commands_tx.send(during_backoff).await.unwrap();
assert!(
timeout(Duration::from_secs(1), rejected)
.await
.unwrap()
.unwrap()
.unwrap_err()
.contains("restarting")
);
wait_for(&status, WorkerState::Starting).await;
assert_eq!(status.read().await.max_context, None);
let (during_startup, rejected) = command(vec![99], 1);
commands_tx.send(during_startup).await.unwrap();
assert!(
timeout(Duration::from_secs(1), rejected)
.await
.unwrap()
.unwrap()
.unwrap_err()
.contains("starting")
);
wait_for(&status, WorkerState::Ready).await;
let (fresh, result) = command(vec![99], 1);
commands_tx.send(fresh).await.unwrap();
let events = timeout(Duration::from_secs(5), result)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(
metrics.started,
metrics.completed,
metrics.failed_or_interrupted
),
(2, 1, 1)
);
assert_eq!(metrics.cancelled, 0);
assert!(metrics.active_since.is_none());
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
2
);
assert_eq!(
std::fs::read_to_string(root.join("requests")).unwrap(),
"GEN 3 10,20\nGEN 1 99\n"
);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn cancelled_command_keeps_drain_guard_until_stop_terminal() {
let (config, root) = restart_fixture("cancel-drain", "drain", 0);
let lifecycle = crate::lifecycle::Lifecycle::default();
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 (events_tx, mut events_rx) = mpsc::channel(2);
commands_tx
.send(GenerationCommand {
queue: None,
activity: Some(lifecycle.generation()),
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: GenerationResult::Streaming(events_tx),
})
.await
.unwrap();
assert_eq!(events_rx.recv().await.unwrap().unwrap(), Event::Token(31));
lifecycle.set_draining(true);
drop(events_rx);
timeout(Duration::from_secs(5), async {
while !root.join("stopped").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
assert_eq!(lifecycle.snapshot().generation_jobs, 1);
assert!(status.read().await.metrics.active_since.is_some());
std::fs::write(root.join("release"), "").unwrap();
timeout(Duration::from_secs(5), async {
while lifecycle.snapshot().generation_jobs != 0 {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
assert_eq!(status.read().await.metrics.cancelled, 1);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn repeated_crashes_exhaust_lifetime_restart_budget() {
let (config, root) = restart_fixture("restart-loop", "loop", 2);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
timeout(
Duration::from_secs(10),
run(config, status.clone(), stop_rx),
)
.await
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.max_context, None);
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
3
);
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn shutdown_during_backoff_prevents_respawn() {
let (config, root) = restart_fixture("restart-loop", "shutdown", 3);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let task = tokio::spawn(run(config, status.clone(), stop_rx));
wait_for(&status, WorkerState::Restarting).await;
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(1), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
1
);
std::fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn startup_failure_is_not_restarted() {
let (config, root) = restart_fixture("restart-bad", "startup", 3);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop_tx, stop_rx) = watch::channel(false);
timeout(Duration::from_secs(5), run(config, status.clone(), stop_rx))
.await
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
.lines()
.count(),
1
);
std::fs::remove_dir_all(root).unwrap();
}
}