Opt-in api_monitor keeps the last 100 requests of the chat, messages and responses dialects; /metrics gains engine, live, requests, totals, hardware, history; ?format=prometheus (or a scraper Accept) renders the same document as gauges and counters. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2157 lines
80 KiB
Rust
2157 lines
80 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, Done, Event, Generate};
|
|
|
|
const STOP_DRAIN_TIMEOUT: Duration = Duration::from_secs(20);
|
|
/// Start of the error a stalled request ends with; the client is told, not just disconnected.
|
|
const STALL_PREFIX: &str = "engine made no progress";
|
|
|
|
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 {
|
|
pub(crate) fn take(&mut self) -> Self {
|
|
std::mem::replace(self, Self::Finished)
|
|
}
|
|
|
|
pub(crate) fn is_closed(&self) -> bool {
|
|
match self {
|
|
Self::Buffered(sender) => sender.is_closed(),
|
|
Self::Streaming(sender) => sender.is_closed(),
|
|
Self::Finished => true,
|
|
}
|
|
}
|
|
|
|
pub(crate) async fn closed(&mut self) {
|
|
match self {
|
|
Self::Buffered(sender) => sender.closed().await,
|
|
Self::Streaming(sender) => sender.closed().await,
|
|
Self::Finished => {}
|
|
}
|
|
}
|
|
|
|
pub(crate) 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,
|
|
/// The engine process was stopped on request (`/unload`, idle unload) or never started
|
|
/// (`lazy`); the next request or `/load` starts it again.
|
|
Unloaded,
|
|
Stopping,
|
|
Failed,
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
pub struct WorkerStatus {
|
|
pub state: WorkerState,
|
|
pub max_context: Option<usize>,
|
|
/// The last context the engine reported; kept while unloaded (`/props`, `/slots`).
|
|
pub known_max_context: Option<usize>,
|
|
/// When a request last started or finished, or the engine became ready.
|
|
pub last_activity: Option<tokio::time::Instant>,
|
|
pub metrics: crate::metrics::GenerationMetrics,
|
|
/// The most output tokens this engine accepts for one request, when it has its own limit (the
|
|
/// runtime gRPC facade does). A default output budget never exceeds it; an explicit request above
|
|
/// it is refused by the worker, not truncated.
|
|
pub output_cap: Option<u32>,
|
|
/// The engine speaks the text-level contract (a runtime backend): per-request token-level features it cannot carry
|
|
/// (`reasoning_budget_tokens`, `strata_tune`, `experimental_speed_projection`) are refused with a 400 by the HTTP layer.
|
|
pub text_level_engine: bool,
|
|
}
|
|
|
|
impl Default for WorkerStatus {
|
|
fn default() -> Self {
|
|
Self {
|
|
state: WorkerState::Unconfigured,
|
|
max_context: None,
|
|
known_max_context: None,
|
|
last_activity: None,
|
|
metrics: crate::metrics::GenerationMetrics::with_history(),
|
|
output_cap: None,
|
|
text_level_engine: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// How to run the command before a reload.
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
|
|
#[serde(untagged)]
|
|
pub enum BeforeLoad {
|
|
/// Run through `sh -c`.
|
|
Shell(String),
|
|
Argv(Vec<String>),
|
|
}
|
|
|
|
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,
|
|
/// Start unloaded: the first request (or `POST /load`) starts the engine.
|
|
pub lazy: bool,
|
|
/// No line from the engine for this long during a request ends it (the stall watchdog seen
|
|
/// from outside; see `leleka_serving_policy::watchdog`). `None` = off.
|
|
pub stall_timeout: Option<Duration>,
|
|
/// Run before every reload and restart (not the first start): e.g. unload another server's model.
|
|
pub before_load: Option<BeforeLoad>,
|
|
/// Reload only when this much VRAM is free (MiB); 0 = always.
|
|
pub min_free_vram_mib: u64,
|
|
/// The image encoder: stopped with the engine, started again before it, and never on the GPU at the same
|
|
/// time as a generation.
|
|
pub vision: Option<Arc<crate::vision::Vision>>,
|
|
}
|
|
|
|
impl Default for WorkerConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
cuda_memory: None,
|
|
executable: OsString::new(),
|
|
args: Vec::new(),
|
|
startup_timeout: Duration::from_secs(600),
|
|
generation_timeout: None,
|
|
max_restarts: 0,
|
|
lazy: false,
|
|
stall_timeout: None,
|
|
before_load: None,
|
|
min_free_vram_mib: 0,
|
|
vision: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Why a load did not happen.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum LoadError {
|
|
/// `min_free_vram_mib` is not free: the model stays unloaded until it is.
|
|
GpuBusy(String),
|
|
Failed(String),
|
|
}
|
|
|
|
pub type LoadReply = oneshot::Sender<Result<(), LoadError>>;
|
|
|
|
/// Administrative commands to the supervisor.
|
|
pub enum Control {
|
|
/// `idle_for`: only if no request ran within that long (the idle thread); `None` is `/unload`.
|
|
Unload {
|
|
idle_for: Option<Duration>,
|
|
reply: oneshot::Sender<leleka_serving_policy::idle::Outcome>,
|
|
},
|
|
/// Start the engine now if it is unloaded; answers when it is ready.
|
|
Load { reply: LoadReply },
|
|
/// Change the inference settings of the running engine (a JSON document); the answer is the effective settings, or
|
|
/// the HTTP status and message of the refusal.
|
|
Reconfigure { settings: String, reply: oneshot::Sender<Result<String, (u16, String)>> },
|
|
}
|
|
|
|
/// Answer a reconfigure that reached a worker which cannot do it.
|
|
pub fn reconfigure_unavailable(reply: oneshot::Sender<Result<String, (u16, String)>>, why: &str) {
|
|
let _ = reply.send(Err((503, why.to_owned())));
|
|
}
|
|
|
|
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>>,
|
|
shutdown: watch::Receiver<bool>,
|
|
requests: mpsc::Receiver<GenerationCommand>,
|
|
) {
|
|
// The sender stays alive for the duration: with no administrative channel, nothing is ever sent.
|
|
let (_idle, control) = mpsc::channel(1);
|
|
run_supervised(config, status, shutdown, requests, control).await;
|
|
}
|
|
|
|
enum Wake {
|
|
Shutdown,
|
|
Load,
|
|
Command(Box<GenerationCommand>),
|
|
}
|
|
|
|
async fn fail_loads(waiting: &mut Vec<LoadReply>, error: &LoadError) {
|
|
for reply in waiting.drain(..) {
|
|
let _ = reply.send(Err(error.clone()));
|
|
}
|
|
}
|
|
|
|
/// Wait while the engine is unloaded for something that needs it.
|
|
async fn wait_unloaded(
|
|
shutdown: &mut watch::Receiver<bool>,
|
|
requests: &mut mpsc::Receiver<GenerationCommand>,
|
|
control: &mut mpsc::Receiver<Control>,
|
|
waiting: &mut Vec<LoadReply>,
|
|
) -> Wake {
|
|
let mut requests_closed = false;
|
|
let mut control_closed = false;
|
|
loop {
|
|
tokio::select! {
|
|
biased;
|
|
_ = shutdown.changed() => return Wake::Shutdown,
|
|
message = control.recv(), if !control_closed => match message {
|
|
Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "the engine is not loaded"),
|
|
Some(Control::Load { reply }) => {
|
|
waiting.push(reply);
|
|
return Wake::Load;
|
|
}
|
|
Some(Control::Unload { reply, .. }) => {
|
|
let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded);
|
|
}
|
|
None => control_closed = true,
|
|
},
|
|
command = requests.recv(), if !requests_closed => match command {
|
|
Some(command) => return Wake::Command(Box::new(command)),
|
|
None => requests_closed = true,
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The checks before an engine is started again (not the first start): the `before_load` command,
|
|
/// then the free-VRAM gate. A failing command is logged and the load goes on, as in the Original.
|
|
async fn reload_gate(config: &WorkerConfig) -> Result<(), LoadError> {
|
|
if let Some(before) = &config.before_load {
|
|
crate::elog!("before loading: {before:?}");
|
|
let mut command = match before {
|
|
BeforeLoad::Shell(line) => {
|
|
let mut c = Command::new("sh");
|
|
c.arg("-c").arg(line);
|
|
c
|
|
}
|
|
BeforeLoad::Argv(argv) if !argv.is_empty() => {
|
|
let mut c = Command::new(&argv[0]);
|
|
c.args(&argv[1..]);
|
|
c
|
|
}
|
|
BeforeLoad::Argv(_) => Command::new("true"),
|
|
};
|
|
command.stdin(Stdio::null()).kill_on_drop(true);
|
|
match command.spawn() {
|
|
Ok(mut child) => match timeout(Duration::from_secs(120), child.wait()).await {
|
|
Ok(Ok(_)) => {}
|
|
Ok(Err(error)) => {
|
|
crate::elog!("the before_load command failed ({error}); loading anyway")
|
|
}
|
|
Err(_) => {
|
|
crate::elog!("the before_load command timed out; loading anyway");
|
|
let _ = child.kill().await;
|
|
}
|
|
},
|
|
Err(error) => crate::elog!("the before_load command failed ({error}); loading anyway"),
|
|
}
|
|
}
|
|
if config.min_free_vram_mib > 0 {
|
|
// Memory another process just gave back can take a moment.
|
|
let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
|
|
let mut free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await;
|
|
while free.is_some_and(|f| f < config.min_free_vram_mib)
|
|
&& tokio::time::Instant::now() < deadline
|
|
{
|
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
|
free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await;
|
|
}
|
|
if let Some(free) = free.filter(|f| *f < config.min_free_vram_mib) {
|
|
return Err(LoadError::GpuBusy(format!(
|
|
"the GPU is in use by another program: {free} MiB of VRAM free, the model needs {} (min_free_vram_mib) - it stays unloaded until that is free",
|
|
config.min_free_vram_mib
|
|
)));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn run_supervised(
|
|
config: WorkerConfig,
|
|
status: Arc<RwLock<WorkerStatus>>,
|
|
mut shutdown: watch::Receiver<bool>,
|
|
mut requests: mpsc::Receiver<GenerationCommand>,
|
|
mut control: mpsc::Receiver<Control>,
|
|
) {
|
|
if config.max_restarts > 3 {
|
|
crate::elog!("worker max_restarts must be between 0 and 3");
|
|
update(&status, WorkerState::Failed, None).await;
|
|
return;
|
|
}
|
|
// A lazy engine has not reported its context yet: `--max-context N` says what it will be.
|
|
if let Some(configured) = config
|
|
.args
|
|
.windows(2)
|
|
.find(|pair| pair[0] == "--max-context")
|
|
.and_then(|pair| pair[1].parse::<usize>().ok())
|
|
.filter(|context| *context > 0)
|
|
{
|
|
status.write().await.known_max_context = Some(configured);
|
|
}
|
|
let mut waiting: Vec<LoadReply> = Vec::new();
|
|
let mut inbox: Option<GenerationCommand> = None;
|
|
let mut unloaded = config.lazy;
|
|
let mut started_before = false;
|
|
let mut attempt: u32 = 0;
|
|
loop {
|
|
if unloaded {
|
|
update(&status, WorkerState::Unloaded, None).await;
|
|
match wait_unloaded(&mut shutdown, &mut requests, &mut control, &mut waiting).await {
|
|
Wake::Shutdown => {
|
|
update(&status, WorkerState::Stopping, None).await;
|
|
return;
|
|
}
|
|
Wake::Load => {}
|
|
Wake::Command(command) => inbox = Some(*command),
|
|
}
|
|
unloaded = false;
|
|
attempt = 0;
|
|
}
|
|
if (started_before || config.lazy)
|
|
&& let Err(error) = reload_gate(&config).await
|
|
{
|
|
let message = match &error {
|
|
LoadError::GpuBusy(m) | LoadError::Failed(m) => m.clone(),
|
|
};
|
|
crate::elog!("{message}");
|
|
fail_loads(&mut waiting, &error).await;
|
|
if let Some(command) = inbox.take() {
|
|
send_failure(command.result, message).await;
|
|
}
|
|
unloaded = true;
|
|
continue;
|
|
}
|
|
// The image encoder first, as at a start: a GPU encoder takes its VRAM before the engine sizes its cache.
|
|
if let Some(vision) = &config.vision
|
|
&& let Err(error) = vision.ensure_running().await
|
|
{
|
|
let message = error.to_string();
|
|
crate::elog!("{message}");
|
|
let error = LoadError::Failed(message.clone());
|
|
fail_loads(&mut waiting, &error).await;
|
|
if let Some(command) = inbox.take() {
|
|
send_failure(command.result, message).await;
|
|
}
|
|
unloaded = true;
|
|
continue;
|
|
}
|
|
started_before = true;
|
|
match run_session(
|
|
&config,
|
|
&status,
|
|
&mut shutdown,
|
|
&mut requests,
|
|
&mut control,
|
|
&mut inbox,
|
|
&mut waiting,
|
|
)
|
|
.await
|
|
{
|
|
SessionExit::Stopped => return,
|
|
SessionExit::StartupFailed => {
|
|
fail_loads(
|
|
&mut waiting,
|
|
&LoadError::Failed("the engine failed to start".into()),
|
|
)
|
|
.await;
|
|
return;
|
|
}
|
|
SessionExit::Unloaded => {
|
|
unloaded = true;
|
|
continue;
|
|
}
|
|
SessionExit::RuntimeFailed if attempt == config.max_restarts => {
|
|
fail_loads(&mut waiting, &LoadError::Failed("the engine failed".into())).await;
|
|
return;
|
|
}
|
|
SessionExit::RuntimeFailed => {}
|
|
}
|
|
update(&status, WorkerState::Restarting, None).await;
|
|
let delay = Duration::from_secs(2 << attempt);
|
|
crate::elog!(
|
|
"Strata engine restart {}/{} in {} seconds",
|
|
attempt + 1,
|
|
config.max_restarts,
|
|
delay.as_secs()
|
|
);
|
|
attempt += 1;
|
|
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,
|
|
Unloaded,
|
|
}
|
|
|
|
async fn run_session(
|
|
config: &WorkerConfig,
|
|
status: &RwLock<WorkerStatus>,
|
|
shutdown: &mut watch::Receiver<bool>,
|
|
requests: &mut mpsc::Receiver<GenerationCommand>,
|
|
control: &mut mpsc::Receiver<Control>,
|
|
inbox: &mut Option<GenerationCommand>,
|
|
waiting: &mut Vec<LoadReply>,
|
|
) -> 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 {
|
|
crate::elog!("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) => {
|
|
crate::elog!("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 mut control_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 => {
|
|
crate::elog!("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;
|
|
}
|
|
message = control.recv(), if !control_closed => {
|
|
match message {
|
|
Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "the engine is starting"),
|
|
// A load that arrives while the engine starts is answered at READY.
|
|
Some(Control::Load { reply }) => waiting.push(reply),
|
|
Some(Control::Unload { reply, .. }) => {
|
|
let _ = reply.send(leleka_serving_policy::idle::Outcome::Busy);
|
|
}
|
|
None => control_closed = true,
|
|
}
|
|
continue;
|
|
}
|
|
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;
|
|
status.write().await.last_activity = Some(tokio::time::Instant::now());
|
|
for reply in waiting.drain(..) {
|
|
let _ = reply.send(Ok(()));
|
|
}
|
|
break max_context;
|
|
}
|
|
crate::elog!("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) => {
|
|
crate::elog!("Strata engine exited before READY");
|
|
terminate(&mut child, &mut stdin).await;
|
|
update(status, WorkerState::Failed, None).await;
|
|
return SessionExit::StartupFailed;
|
|
}
|
|
Err(error) => {
|
|
crate::elog!("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() => {
|
|
crate::elog!("Strata engine exited: {result:?}");
|
|
update(status, WorkerState::Failed, None).await;
|
|
return SessionExit::RuntimeFailed;
|
|
},
|
|
message = control.recv(), if !control_closed => {
|
|
match message {
|
|
Some(Control::Reconfigure { reply, .. }) => reconfigure_unavailable(reply, "this engine cannot be reconfigured at run time"),
|
|
Some(Control::Load { reply }) => {
|
|
let _ = reply.send(Ok(()));
|
|
}
|
|
Some(Control::Unload { idle_for, reply }) => {
|
|
let idle_s = status
|
|
.read()
|
|
.await
|
|
.last_activity
|
|
.map_or(f64::MAX, |at| at.elapsed().as_secs_f64());
|
|
let outcome = leleka_serving_policy::idle::decide(
|
|
leleka_serving_policy::idle::Situation {
|
|
supported: true,
|
|
loaded: true,
|
|
busy: inbox.is_some() || !requests.is_empty(),
|
|
idle_s,
|
|
},
|
|
idle_for.map(|d| d.as_secs_f64()),
|
|
);
|
|
if outcome == leleka_serving_policy::idle::Outcome::Unloaded {
|
|
update(status, WorkerState::Unloaded, None).await;
|
|
stop(&mut child, &mut stdin).await;
|
|
if let Some(vision) = &config.vision {
|
|
vision.unload().await;
|
|
}
|
|
let _ = reply.send(outcome);
|
|
return SessionExit::Unloaded;
|
|
}
|
|
let _ = reply.send(outcome);
|
|
}
|
|
None => control_closed = true,
|
|
}
|
|
},
|
|
command = async {
|
|
match inbox.take() {
|
|
Some(command) => Some(command),
|
|
None => requests.recv().await,
|
|
}
|
|
}, if !requests_closed => {
|
|
match command {
|
|
Some(mut command) => {
|
|
if command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim()) {
|
|
continue;
|
|
}
|
|
status.write().await.last_activity = Some(tokio::time::Instant::now());
|
|
// Retain the command activity until protocol cleanup,
|
|
// including STOP/QUIT and failed-process termination.
|
|
let _activity = command.activity.take();
|
|
// The encoder and the engine never use the GPU at the same time.
|
|
let _turn = match &config.vision {
|
|
Some(vision) => Some(vision.gate.clone().lock_owned().await),
|
|
None => None,
|
|
};
|
|
tokio::select! {
|
|
(timed_out, result) = async {
|
|
let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status, config.stall_timeout);
|
|
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 {
|
|
crate::elog!("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 || error.starts_with(STALL_PREFIX) {
|
|
let _ = timeout(Duration::from_secs(1), send_failure(command.result, error)).await;
|
|
}
|
|
return SessionExit::RuntimeFailed;
|
|
}
|
|
status.write().await.last_activity = Some(tokio::time::Instant::now());
|
|
}
|
|
_ = shutdown.changed() => {
|
|
update(status, WorkerState::Stopping, None).await;
|
|
stop_active(&mut child, &mut stdin).await;
|
|
return SessionExit::Stopped;
|
|
}
|
|
}
|
|
}
|
|
None => requests_closed = true,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Add up one pass's `DONE` counters (reasoning-budget passes report separately).
|
|
fn add_opt(total: Option<u64>, part: Option<u64>) -> Option<u64> {
|
|
match (total, part) {
|
|
(None, None) => None,
|
|
(a, b) => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))),
|
|
}
|
|
}
|
|
|
|
/// What the client sees after a budget wrap-up: one `DONE` for the whole request.
|
|
fn combine_done(first: &Done, passes: &[Done], generated: u64, finish: wire::Finish) -> Done {
|
|
let mut done = Done {
|
|
generated,
|
|
prompt_tokens: first.prompt_tokens,
|
|
prompt_ms: 0.0,
|
|
decode_ms: 0.0,
|
|
finish,
|
|
drafts_accepted: None,
|
|
drafts_offered: None,
|
|
// Only what the caller's own prompt reused: the tokens of the first pass's prefix, not the
|
|
// generated text the second pass re-reads from the engine's own cache.
|
|
reused: first.reused,
|
|
expert_hits: None,
|
|
expert_lookups: None,
|
|
};
|
|
for pass in passes {
|
|
done.prompt_ms += pass.prompt_ms;
|
|
done.decode_ms += pass.decode_ms;
|
|
done.drafts_accepted = add_opt(done.drafts_accepted, pass.drafts_accepted);
|
|
done.drafts_offered = add_opt(done.drafts_offered, pass.drafts_offered);
|
|
done.expert_hits = add_opt(done.expert_hits, pass.expert_hits);
|
|
done.expert_lookups = add_opt(done.expert_lookups, pass.expert_lookups);
|
|
}
|
|
done
|
|
}
|
|
|
|
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>,
|
|
stall_timeout: Option<Duration>,
|
|
) -> 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);
|
|
|
|
// Reasoning budget (issue #123): the thinking is wrapped up at the budget and generation goes on.
|
|
let mut budget = command.request.reasoning.clone().map(|plan| {
|
|
(
|
|
leleka_serving_policy::reasoning::BudgetTracker::new(plan.budget),
|
|
plan,
|
|
)
|
|
});
|
|
let budgeted = budget.is_some();
|
|
let mut generated: u64 = 0; // tokens delivered to the client, wrap-up included
|
|
let mut segment: Vec<u32> = Vec::new(); // this pass's delivered tokens
|
|
let mut prompt: Vec<u32> = if budgeted {
|
|
command.request.token_ids.clone()
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
let mut wrap_pending = false; // a wrap-up STOP is in flight: tokens until its DONE are discarded
|
|
let mut passes: Vec<Done> = Vec::new();
|
|
let mut first_pass = true;
|
|
|
|
// The stall watchdog seen from outside: one poll a second over the engine's lines.
|
|
let started = tokio::time::Instant::now();
|
|
let mut lines_read: u64 = 0;
|
|
let mut dog = stall_timeout.map(|limit| {
|
|
leleka_serving_policy::watchdog::StallWatchdog::new(
|
|
i64::try_from(limit.as_secs().max(1)).unwrap_or(i64::MAX),
|
|
0,
|
|
leleka_serving_policy::watchdog::Counters {
|
|
beats: 0,
|
|
busy: true,
|
|
ticks: 0,
|
|
},
|
|
)
|
|
});
|
|
let mut ticker = tokio::time::interval(Duration::from_secs(1));
|
|
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
|
ticker.reset();
|
|
|
|
loop {
|
|
let line = tokio::select! {
|
|
biased;
|
|
_ = &mut stop_deadline, if stopped || wrap_pending => {
|
|
return Err("engine did not terminate generation within 20 seconds of STOP".to_owned());
|
|
}
|
|
_ = command.result.closed(), if !stopped => {
|
|
if !wrap_pending {
|
|
pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?;
|
|
pipe.flush().await.map_err(|error| error.to_string())?;
|
|
stop_deadline.as_mut().reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT);
|
|
}
|
|
stopped = true;
|
|
continue;
|
|
}
|
|
_ = ticker.tick(), if dog.is_some() => {
|
|
if let Some(dog) = dog.as_mut()
|
|
&& let leleka_serving_policy::watchdog::Verdict::Stalled { quiet_ms, .. } = dog.poll(
|
|
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
|
|
leleka_serving_policy::watchdog::Counters { beats: lines_read, busy: true, ticks: 0 },
|
|
)
|
|
{
|
|
return Err(format!(
|
|
"{STALL_PREFIX} for {} s during a request (stall watchdog)",
|
|
quiet_ms / 1000
|
|
));
|
|
}
|
|
continue;
|
|
}
|
|
line = lines.next_line() => line.map_err(|error| error.to_string())?,
|
|
}
|
|
.ok_or("engine exited before a terminal line")?;
|
|
lines_read = lines_read.wrapping_add(1);
|
|
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::Done(done)) => {
|
|
let disconnected = stopped || command.result.is_closed();
|
|
if wrap_pending && !disconnected {
|
|
// The budget was reached: close the thinking and let the model answer.
|
|
wrap_pending = false;
|
|
passes.push(done);
|
|
let Some((_, plan)) = budget.take() else {
|
|
return Err("reasoning budget state lost".into());
|
|
};
|
|
let room = i64::from(command.request.max_new)
|
|
- i64::try_from(generated).unwrap_or(i64::MAX)
|
|
- i64::try_from(plan.wrap_up.len()).unwrap_or(i64::MAX);
|
|
if room < 1 {
|
|
// No room left to answer: "length", as without a budget.
|
|
let combined =
|
|
combine_done(&passes[0], &passes, generated, wire::Finish::Length);
|
|
return finish(command, events, combined, false, status).await;
|
|
}
|
|
crate::elog!(
|
|
"thinking budget reached ({} tokens): wrapping up the thinking",
|
|
plan.budget
|
|
);
|
|
for id in &plan.wrap_up {
|
|
generated += 1;
|
|
deliver(command, &mut events, Event::Token(*id)).await;
|
|
}
|
|
prompt.extend_from_slice(&segment);
|
|
prompt.extend_from_slice(&plan.wrap_up);
|
|
segment.clear();
|
|
let next = Generate {
|
|
token_ids: prompt.clone(),
|
|
max_new: u32::try_from(
|
|
i64::from(command.request.max_new)
|
|
- i64::try_from(generated).unwrap_or(i64::MAX),
|
|
)
|
|
.unwrap_or(1),
|
|
reasoning: None,
|
|
..command.request.clone()
|
|
};
|
|
let next_line = next.line().map_err(str::to_owned)?;
|
|
pipe.write_all(next_line.as_bytes())
|
|
.await
|
|
.map_err(|error| error.to_string())?;
|
|
pipe.flush().await.map_err(|error| error.to_string())?;
|
|
first_pass = false;
|
|
continue;
|
|
}
|
|
let done_out = if passes.is_empty() {
|
|
done
|
|
} else {
|
|
passes.push(done.clone());
|
|
combine_done(&passes[0], &passes, generated, done.finish)
|
|
};
|
|
return finish(command, events, done_out, disconnected, status).await;
|
|
}
|
|
Some(Event::PromptProgress { .. }) if !first_pass => {}
|
|
Some(_) if stopped || wrap_pending => {}
|
|
Some(event) => {
|
|
if let (Event::Token(id), Some((tracker, plan))) = (&event, budget.as_mut()) {
|
|
generated += 1;
|
|
segment.push(*id);
|
|
let verdict = if plan.stop_ids.contains(id) {
|
|
leleka_serving_policy::reasoning::Verdict::Continue
|
|
} else {
|
|
tracker.push(&(plan.token_bytes)(*id))
|
|
};
|
|
deliver(command, &mut events, event).await;
|
|
if verdict == leleka_serving_policy::reasoning::Verdict::WrapUp {
|
|
pipe.write_all(b"STOP\n")
|
|
.await
|
|
.map_err(|error| error.to_string())?;
|
|
pipe.flush().await.map_err(|error| error.to_string())?;
|
|
wrap_pending = true;
|
|
stop_deadline
|
|
.as_mut()
|
|
.reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT);
|
|
}
|
|
} else {
|
|
if matches!(event, Event::Token(_)) {
|
|
generated += 1;
|
|
}
|
|
deliver(command, &mut events, event).await;
|
|
}
|
|
}
|
|
None => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Hand one event to the client side (buffered or streamed).
|
|
pub(crate) async fn deliver(command: &GenerationCommand, events: &mut Vec<Event>, event: Event) {
|
|
match &command.result {
|
|
GenerationResult::Buffered(_) => events.push(event),
|
|
GenerationResult::Streaming(_) => command.result.send_event(event).await,
|
|
GenerationResult::Finished => {}
|
|
}
|
|
}
|
|
|
|
/// The terminal event: hand `done` to the client and record the generation.
|
|
pub(crate) async fn finish(
|
|
command: &mut GenerationCommand,
|
|
mut events: Vec<Event>,
|
|
done: Done,
|
|
disconnected: bool,
|
|
status: &RwLock<WorkerStatus>,
|
|
) -> Result<(), String> {
|
|
// One line per generation: the operator's only per-request record (no prompt or output text). The time is taken now; the
|
|
// line is written after the client side has the terminal event, so a slow log sink never delays a response.
|
|
let finished_ms = unix_ms();
|
|
let event = Event::Done(done.clone());
|
|
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 => {}
|
|
}
|
|
crate::elog!(
|
|
"generation done: t_unix_ms={} finish={:?} prompt_tokens={} reused={} generated={} prompt_ms={:.1} decode_ms={:.1} disconnected={}",
|
|
finished_ms,
|
|
done.finish,
|
|
done.prompt_tokens,
|
|
done.reused.unwrap_or(0),
|
|
done.generated,
|
|
done.prompt_ms,
|
|
done.decode_ms,
|
|
disconnected
|
|
);
|
|
status.write().await.metrics.finish(&done, disconnected);
|
|
Ok(())
|
|
}
|
|
|
|
/// Wall-clock milliseconds for log lines that are joined with client-side timestamps.
|
|
pub(crate) fn unix_ms() -> u128 {
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.map_or(0, |d| d.as_millis())
|
|
}
|
|
|
|
pub(crate) 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)
|
|
}
|
|
|
|
pub(crate) 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;
|
|
if max_context.is_some() {
|
|
status.known_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,
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
sampling: leleka_sampler_ref::RequestSampling {
|
|
temperature: Some(0.5),
|
|
top_p: Some(0.9),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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,
|
|
..Default::default()
|
|
},
|
|
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();
|
|
}
|
|
|
|
// ---- load, unload, lazy start, reload gate, reasoning budget, stall watchdog -----------------
|
|
|
|
fn scratch(name: &str) -> std::path::PathBuf {
|
|
let dir = std::env::temp_dir().join(format!("strata-worker-{}-{name}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
dir
|
|
}
|
|
|
|
fn lines_of(path: &Path) -> usize {
|
|
std::fs::read_to_string(path).map_or(0, |text| text.lines().count())
|
|
}
|
|
|
|
struct Supervised {
|
|
status: Arc<RwLock<WorkerStatus>>,
|
|
requests: mpsc::Sender<GenerationCommand>,
|
|
control: mpsc::Sender<Control>,
|
|
stop: watch::Sender<bool>,
|
|
task: tokio::task::JoinHandle<()>,
|
|
}
|
|
|
|
fn supervise(config: WorkerConfig) -> Supervised {
|
|
let status = Arc::new(RwLock::new(WorkerStatus::default()));
|
|
let (stop, stop_rx) = watch::channel(false);
|
|
let (requests, requests_rx) = mpsc::channel(4);
|
|
let (control, control_rx) = mpsc::channel(4);
|
|
let task = tokio::spawn(run_supervised(
|
|
config,
|
|
status.clone(),
|
|
stop_rx,
|
|
requests_rx,
|
|
control_rx,
|
|
));
|
|
Supervised {
|
|
status,
|
|
requests,
|
|
control,
|
|
stop,
|
|
task,
|
|
}
|
|
}
|
|
|
|
impl Supervised {
|
|
async fn unload(&self, idle_for: Option<Duration>) -> leleka_serving_policy::idle::Outcome {
|
|
let (reply, answer) = oneshot::channel();
|
|
self.control
|
|
.send(Control::Unload { idle_for, reply })
|
|
.await
|
|
.unwrap();
|
|
timeout(Duration::from_secs(10), answer)
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
}
|
|
|
|
async fn load(&self) -> Result<(), LoadError> {
|
|
let (reply, answer) = oneshot::channel();
|
|
self.control.send(Control::Load { reply }).await.unwrap();
|
|
timeout(Duration::from_secs(10), answer)
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
}
|
|
|
|
async fn generate(&self, request: Generate) -> Result<Vec<Event>, String> {
|
|
let (result, received) = oneshot::channel();
|
|
self.requests
|
|
.send(GenerationCommand {
|
|
queue: None,
|
|
activity: None,
|
|
request,
|
|
result: GenerationResult::Buffered(result),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
timeout(Duration::from_secs(10), received)
|
|
.await
|
|
.expect("generation answer")
|
|
.unwrap()
|
|
}
|
|
|
|
async fn shutdown(self) {
|
|
self.stop.send(true).unwrap();
|
|
timeout(Duration::from_secs(25), self.task)
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
}
|
|
}
|
|
|
|
fn lifecycle_request() -> Generate {
|
|
Generate {
|
|
token_ids: vec![1, 2],
|
|
max_new: 2,
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn unload_stops_the_engine_and_the_next_command_loads_it_again() {
|
|
use leleka_serving_policy::idle::Outcome;
|
|
let dir = scratch("unload");
|
|
let mut config = fixture_config("lifecycle", 5);
|
|
config.args.push(dir.to_string_lossy().into_owned());
|
|
let worker = supervise(config);
|
|
wait_for(&worker.status, WorkerState::Ready).await;
|
|
assert_eq!(worker.status.read().await.known_max_context, Some(4096));
|
|
assert_eq!(worker.unload(None).await, Outcome::Unloaded);
|
|
wait_for(&worker.status, WorkerState::Unloaded).await;
|
|
{
|
|
let status = worker.status.read().await;
|
|
assert_eq!(status.max_context, None);
|
|
assert_eq!(
|
|
status.known_max_context,
|
|
Some(4096),
|
|
"the last context survives an unload"
|
|
);
|
|
}
|
|
assert_eq!(
|
|
lines_of(&dir.join("quits")),
|
|
1,
|
|
"the engine is asked to QUIT, not killed"
|
|
);
|
|
assert_eq!(worker.unload(None).await, Outcome::NotLoaded);
|
|
// A command that arrives while unloaded starts the engine and is served.
|
|
let events = worker.generate(lifecycle_request()).await.unwrap();
|
|
assert_eq!(events[..2], [Event::Token(31), Event::Token(32)]);
|
|
assert_eq!(worker.status.read().await.state, WorkerState::Ready);
|
|
assert_eq!(lines_of(&dir.join("boots")), 2);
|
|
worker.shutdown().await;
|
|
std::fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn lazy_start_waits_for_load_and_load_is_idempotent() {
|
|
let dir = scratch("lazy");
|
|
let mut config = fixture_config("lifecycle", 5);
|
|
config.args.push(dir.to_string_lossy().into_owned());
|
|
config.lazy = true;
|
|
let worker = supervise(config);
|
|
wait_for(&worker.status, WorkerState::Unloaded).await;
|
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
|
assert_eq!(
|
|
lines_of(&dir.join("boots")),
|
|
0,
|
|
"no process before the first load"
|
|
);
|
|
worker.load().await.unwrap();
|
|
assert_eq!(worker.status.read().await.state, WorkerState::Ready);
|
|
worker.load().await.unwrap();
|
|
assert_eq!(lines_of(&dir.join("boots")), 1);
|
|
worker.shutdown().await;
|
|
std::fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn idle_unload_waits_for_the_idle_period_and_for_queued_work() {
|
|
use leleka_serving_policy::idle::Outcome;
|
|
let dir = scratch("idle");
|
|
let mut config = fixture_config("lifecycle", 5);
|
|
config.args.push(dir.to_string_lossy().into_owned());
|
|
let worker = supervise(config);
|
|
wait_for(&worker.status, WorkerState::Ready).await;
|
|
assert_eq!(
|
|
worker.unload(Some(Duration::from_secs(3600))).await,
|
|
Outcome::Busy
|
|
);
|
|
assert_eq!(worker.status.read().await.state, WorkerState::Ready);
|
|
tokio::time::sleep(Duration::from_millis(1100)).await;
|
|
assert_eq!(
|
|
worker.unload(Some(Duration::from_secs(1))).await,
|
|
Outcome::Unloaded
|
|
);
|
|
wait_for(&worker.status, WorkerState::Unloaded).await;
|
|
worker.shutdown().await;
|
|
std::fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_before_load_command_runs_on_reload_but_not_on_the_first_start() {
|
|
let dir = scratch("gate");
|
|
let marker = dir.join("before");
|
|
let mut config = fixture_config("lifecycle", 5);
|
|
config.args.push(dir.to_string_lossy().into_owned());
|
|
config.before_load = Some(BeforeLoad::Shell(format!(
|
|
"echo hook >> {}",
|
|
marker.display()
|
|
)));
|
|
let worker = supervise(config);
|
|
wait_for(&worker.status, WorkerState::Ready).await;
|
|
assert_eq!(lines_of(&marker), 0);
|
|
worker.unload(None).await;
|
|
worker.load().await.unwrap();
|
|
assert_eq!(lines_of(&marker), 1);
|
|
worker.unload(None).await;
|
|
worker.load().await.unwrap();
|
|
assert_eq!(lines_of(&marker), 2);
|
|
worker.shutdown().await;
|
|
std::fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
fn budget_request(max_new: u32) -> Generate {
|
|
Generate {
|
|
token_ids: vec![10, 20],
|
|
max_new,
|
|
sampling: leleka_sampler_ref::RequestSampling {
|
|
temperature: Some(0.7),
|
|
..Default::default()
|
|
},
|
|
reasoning: Some(crate::wire::ReasoningPlan {
|
|
budget: 3,
|
|
wrap_up: vec![90, 91],
|
|
stop_ids: vec![248046],
|
|
token_bytes: Arc::new(|id| vec![b'a' + (id % 26) as u8]),
|
|
}),
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn reasoning_budget_wraps_up_and_continues_from_the_prefix() {
|
|
let dir = scratch("budget");
|
|
let mut config = fixture_config("budget", 5);
|
|
config.args.push(dir.to_string_lossy().into_owned());
|
|
let worker = supervise(config);
|
|
wait_for(&worker.status, WorkerState::Ready).await;
|
|
let events = worker.generate(budget_request(40)).await.unwrap();
|
|
let tokens: Vec<u32> = events
|
|
.iter()
|
|
.filter_map(|e| match e {
|
|
Event::Token(id) => Some(*id),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
// Tokens 34 and 35 came after the budget point and are discarded; the wrap-up text is
|
|
// delivered as generated tokens, then the continuation.
|
|
assert_eq!(tokens, vec![31, 32, 33, 90, 91, 40, 41]);
|
|
let progress: Vec<_> = events
|
|
.iter()
|
|
.filter(|e| matches!(e, Event::PromptProgress { .. }))
|
|
.collect();
|
|
assert_eq!(
|
|
progress.len(),
|
|
1,
|
|
"only the first pass reports prompt progress"
|
|
);
|
|
let Some(Event::Done(done)) = events.last() else {
|
|
panic!("expected DONE")
|
|
};
|
|
assert_eq!(done.generated, 7);
|
|
assert_eq!(
|
|
done.prompt_tokens, 2,
|
|
"the caller's prompt, not the re-read prefix"
|
|
);
|
|
assert_eq!(done.reused, Some(0));
|
|
assert_eq!(done.finish, wire::Finish::Stop);
|
|
assert_eq!((done.prompt_ms, done.decode_ms), (4.0, 6.0));
|
|
assert_eq!((done.expert_hits, done.expert_lookups), (Some(5), Some(10)));
|
|
assert_eq!(
|
|
std::fs::read_to_string(dir.join("requests"))
|
|
.unwrap()
|
|
.lines()
|
|
.count(),
|
|
2
|
|
);
|
|
let metrics = worker.status.read().await.metrics;
|
|
assert_eq!((metrics.started, metrics.completed), (1, 1));
|
|
assert_eq!(metrics.done_generated_tokens, 7);
|
|
worker.shutdown().await;
|
|
std::fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn reasoning_budget_without_room_to_answer_ends_as_length() {
|
|
let dir = scratch("budget-length");
|
|
let mut config = fixture_config("budget", 5);
|
|
config.args.push(dir.to_string_lossy().into_owned());
|
|
let worker = supervise(config);
|
|
wait_for(&worker.status, WorkerState::Ready).await;
|
|
let events = worker.generate(budget_request(5)).await.unwrap();
|
|
let tokens: Vec<u32> = events
|
|
.iter()
|
|
.filter_map(|e| match e {
|
|
Event::Token(id) => Some(*id),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
tokens,
|
|
vec![31, 32, 33],
|
|
"no wrap-up fits: nothing is appended"
|
|
);
|
|
let Some(Event::Done(done)) = events.last() else {
|
|
panic!("expected DONE")
|
|
};
|
|
assert_eq!((done.generated, done.finish), (3, wire::Finish::Length));
|
|
assert_eq!(
|
|
std::fs::read_to_string(dir.join("requests"))
|
|
.unwrap()
|
|
.lines()
|
|
.count(),
|
|
1
|
|
);
|
|
worker.shutdown().await;
|
|
std::fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_stall_watchdog_ends_a_request_that_makes_no_progress() {
|
|
let mut config = fixture_config("stall", 5);
|
|
config.stall_timeout = Some(Duration::from_secs(1));
|
|
let worker = supervise(config);
|
|
wait_for(&worker.status, WorkerState::Ready).await;
|
|
let started = std::time::Instant::now();
|
|
let error = worker
|
|
.generate(Generate {
|
|
token_ids: vec![1],
|
|
max_new: 1,
|
|
..Default::default()
|
|
})
|
|
.await;
|
|
assert!(started.elapsed() < Duration::from_secs(8));
|
|
let message = error.unwrap_err();
|
|
assert!(
|
|
message.starts_with("engine made no progress for"),
|
|
"{message}"
|
|
);
|
|
// The engine is ended and marked failed (no restarts are configured here).
|
|
wait_for(&worker.status, WorkerState::Failed).await;
|
|
let _ = worker.stop.send(true);
|
|
let _ = timeout(Duration::from_secs(25), worker.task).await;
|
|
}
|
|
}
|