Files
leleka/control-plane/src/worker.rs
T
Pavlo Ratushnyi 5dc28316ab STRA-338 S7: split worker, vision, prometheus, service_install and config by responsibility; name the modules after what they hold
* worker.rs (1271 lines, 1120 of them tests) is 149 lines; the supervisor tests are worker/tests.rs (shared fixtures) and
  worker/tests/{deadlines,handshake,generation,restart,lifecycle,reasoning}.rs. The test names are unchanged; their path
  gains the topic module (worker::tests::restart::..., see scripts/dev/test-outcomes.py compare: 23 MOVED, outcomes equal).
* vision.rs 402 -> 120 lines (tests are vision/tests.rs, same test ids); prometheus.rs 441 -> 50 (the series table is
  prometheus/series.rs); service_install.rs 436 -> 30 (the unix half is service_install/unix.rs and unix/tests.rs, same ids).
* config: Config::load_with_path (430 lines in one function) hands its limits, engine-worker and MCP sections to
  config/methods/load_sections.rs; the same checks run in the same order with the same messages.
* mcp, request_log, vision, worker, config: impl_*/note_*/check_* file names are now hub.rs, server.rs, stdio_transport.rs,
  http_transport.rs, parse_config.rs, obs_handle.rs, engine_counters.rs, encoder.rs, cleanup.rs, generation_result.rs, ...
  Public paths are unchanged (the modules re-export with glob as before).

Architecture gate: five oversize entries leave the baseline (worker.rs, vision.rs, prometheus.rs, service_install.rs,
config impl_config_2_2.rs); no number rose.
2026-11-05 20:33:04 +01:00

150 lines
4.8 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,
}
#[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,
}
/// 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>>,
}
/// 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)>>,
},
}
enum Wake {
Shutdown,
Load,
Command(Box<GenerationCommand>),
}
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::*;