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, pub activity: Option, pub request: Generate, pub result: GenerationResult, } pub enum GenerationResult { Buffered(oneshot::Sender, String>>), Streaming(mpsc::Sender>), Finished, } #[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, /// The last context the engine reported; kept while unloaded (`/props`, `/slots`). pub known_max_context: Option, /// When a request last started or finished, or the engine became ready. pub last_activity: Option, 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, /// 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, } /// 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), } pub struct WorkerConfig { pub cuda_memory: Option, pub executable: OsString, pub args: Vec, pub startup_timeout: Duration, pub generation_timeout: Option, 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, /// Run before every reload and restart (not the first start): e.g. unload another server's model. pub before_load: Option, /// 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>, } /// 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>; /// 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, reply: oneshot::Sender, }, /// 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>, }, } enum Wake { Shutdown, Load, Command(Box), } enum SessionExit { Stopped, StartupFailed, RuntimeFailed, Unloaded, } #[cfg(all(test, unix))] mod tests; mod generation_result; #[allow(unused_imports)] pub use generation_result::*; mod run_supervised; #[allow(unused_imports)] pub use run_supervised::*; mod run_session; #[allow(unused_imports)] pub use run_session::*; mod combine_done; #[allow(unused_imports)] pub use combine_done::*; mod finish; #[allow(unused_imports)] pub use finish::*;