diff --git a/architecture-baseline.json b/architecture-baseline.json index cdc2229c..30019d75 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -9,7 +9,7 @@ "control-plane/src/config/impl_config/impl_config_2_2.rs": 434, "control-plane/src/ggml_bridge/tests.rs": 1286, "control-plane/src/gguf_f32_stream/tests.rs": 909, - "control-plane/src/main.rs": 1156, + "control-plane/src/main.rs": 1155, "control-plane/src/prepare_preview/tests.rs": 808, "control-plane/src/prometheus.rs": 441, "control-plane/src/responses/tests.rs": 2961, @@ -147,7 +147,7 @@ "dyn-trait:leleka-model-format": 8, "dyn-trait:leleka-runtime": 70, "dyn-trait:leleka-tokenizer": 2, - "dyn-trait:strata-control": 35, + "dyn-trait:strata-control": 21, "dyn-trait:strata-desktop-core": 2, "env-read:leleka-cpu-kernels": 1, "env-read:leleka-cpu-worker": 2, diff --git a/control-plane/examples/cp_replay.rs b/control-plane/examples/cp_replay.rs index 5d976de6..96f25534 100644 --- a/control-plane/examples/cp_replay.rs +++ b/control-plane/examples/cp_replay.rs @@ -282,7 +282,7 @@ where tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared( tokenizer.clone(), ))), - generation: Some(requests), + engine: Some(strata_control::adapters::ChannelEngine::shared(requests)), control: Some(control), ..Default::default() }; diff --git a/control-plane/src/adapters.rs b/control-plane/src/adapters.rs new file mode 100644 index 00000000..f7450025 --- /dev/null +++ b/control-plane/src/adapters.rs @@ -0,0 +1,17 @@ +//! Adapters of the gateway ports (STRA-338 S16): the real implementations `main` composes. +//! +//! * `channel_engine`: `EngineClient` over the `mpsc` channel the worker supervisors, the runtime backend worker and the +//! pool dispatcher read. +//! * `system_clock`: `Clock` over the operating system. +//! * `mcp_tool_hub`: `ToolHub` over `mcp::Hub`. +//! * `vision_encoder`: `VisionEncoder` over the `strata-vision` process (`vision::Vision`). +//! +//! The response store adapter lives with the history it wraps, in `responses::history_adapter`. + +pub mod channel_engine; +pub mod mcp_tool_hub; +pub mod system_clock; +pub mod vision_encoder; + +pub use channel_engine::ChannelEngine; +pub use system_clock::SystemClock; diff --git a/control-plane/src/adapters/channel_engine.rs b/control-plane/src/adapters/channel_engine.rs new file mode 100644 index 00000000..767b0120 --- /dev/null +++ b/control-plane/src/adapters/channel_engine.rs @@ -0,0 +1,92 @@ +//! `EngineClient` over the command channel. + +use std::{sync::Arc, time::Duration}; + +use tokio::sync::mpsc; + +use super::SystemClock; +use crate::{ + ports::{BoxFuture, EngineClient, SharedClock, SharedEngine}, + queue::{self, Error}, + worker::GenerationCommand, +}; + +pub struct ChannelEngine { + sender: mpsc::Sender, + clock: SharedClock, +} + +impl ChannelEngine { + pub fn new(sender: mpsc::Sender, clock: SharedClock) -> Self { + Self { sender, clock } + } + + /// A command channel of `capacity` places and its engine; the worker side reads the receiver. + pub fn channel( + capacity: usize, + clock: SharedClock, + ) -> (SharedEngine, mpsc::Receiver) { + let (sender, receiver) = mpsc::channel(capacity); + (Arc::new(Self::new(sender, clock)), receiver) + } + + /// The engine of a channel with the system clock. + pub fn shared(sender: mpsc::Sender) -> SharedEngine { + Arc::new(Self::new(sender, SystemClock::shared())) + } +} + +impl EngineClient for ChannelEngine { + fn submit( + &self, + command: GenerationCommand, + budget: Option, + ) -> BoxFuture<'_, Result<(), Error>> { + Box::pin(queue::enqueue_with( + &self.sender, + command, + budget, + self.clock.clone(), + )) + } + + fn queue_capacity(&self) -> usize { + self.sender.max_capacity() + } + + fn queue_used(&self) -> usize { + self.sender.max_capacity() - self.sender.capacity() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + wire::Generate, + worker::{GenerationCommand, GenerationResult}, + }; + use tokio::sync::oneshot; + + fn command() -> GenerationCommand { + let (result, _received) = oneshot::channel(); + GenerationCommand { + queue: None, + activity: None, + request: Generate::default(), + result: GenerationResult::Buffered(result), + } + } + + #[tokio::test] + async fn submit_puts_the_command_on_the_channel_and_reports_the_queue() { + let (sender, mut receiver) = mpsc::channel(4); + let engine = ChannelEngine::shared(sender); + assert_eq!((engine.queue_capacity(), engine.queue_used()), (4, 0)); + engine.submit(command(), None).await.unwrap(); + assert_eq!(engine.queue_used(), 1); + assert!(receiver.recv().await.is_some()); + drop(receiver); + assert_eq!(engine.submit(command(), None).await, Err(Error::Closed)); + } +} diff --git a/control-plane/src/adapters/mcp_tool_hub.rs b/control-plane/src/adapters/mcp_tool_hub.rs new file mode 100644 index 00000000..d3e2cd72 --- /dev/null +++ b/control-plane/src/adapters/mcp_tool_hub.rs @@ -0,0 +1,31 @@ +//! `ToolHub` over the MCP hub. + +use serde_json::Value; + +use crate::{ + mcp::{CallOutput, Cancel, Hub, McpError}, + ports::{BoxFuture, ToolHub}, +}; + +impl ToolHub for Hub { + fn status(&self) -> BoxFuture<'_, Value> { + Box::pin(Hub::status(self)) + } + + fn template_tools<'a>(&'a self, exclude: &'a [String]) -> BoxFuture<'a, Vec> { + Box::pin(Hub::template_tools(self, exclude)) + } + + fn call<'a>( + &'a self, + name: &'a str, + arguments: Value, + cancel: Option, + ) -> BoxFuture<'a, Result> { + Box::pin(Hub::call(self, name, arguments, cancel)) + } + + fn close(&self) -> BoxFuture<'_, ()> { + Box::pin(Hub::close(self)) + } +} diff --git a/control-plane/src/adapters/system_clock.rs b/control-plane/src/adapters/system_clock.rs new file mode 100644 index 00000000..404a98e9 --- /dev/null +++ b/control-plane/src/adapters/system_clock.rs @@ -0,0 +1,26 @@ +//! `Clock` over the operating system. + +use std::time::SystemTime; + +use tokio::time::Instant; + +use crate::ports::{Clock, SharedClock}; + +#[derive(Clone, Copy, Debug, Default)] +pub struct SystemClock; + +impl SystemClock { + pub fn shared() -> SharedClock { + std::sync::Arc::new(Self) + } +} + +impl Clock for SystemClock { + fn now(&self) -> Instant { + Instant::now() + } + + fn system_time(&self) -> SystemTime { + SystemTime::now() + } +} diff --git a/control-plane/src/adapters/vision_encoder.rs b/control-plane/src/adapters/vision_encoder.rs new file mode 100644 index 00000000..78e029cf --- /dev/null +++ b/control-plane/src/adapters/vision_encoder.rs @@ -0,0 +1,32 @@ +//! `VisionEncoder` over the resident `strata-vision` process. + +use std::path::PathBuf; + +use crate::{ + ports::{BoxFuture, VisionEncoder}, + vision::{Encoded, Keep, Vision, VisionError}, +}; + +impl VisionEncoder for Vision { + fn encode_all<'a>( + &'a self, + sources: &'a [String], + ) -> BoxFuture<'a, Result, VisionError>> { + Box::pin(async move { + // Encode only while the engine is idle: the gate is also taken for every engine generation. + let _turn = self.gate.lock().await; + let mut encoded = Vec::with_capacity(sources.len()); + for source in sources { + encoded.push(self.encode(source).await?); + } + Ok(encoded) + }) + } + + fn combine<'a>( + &'a self, + images: &'a [Encoded], + ) -> BoxFuture<'a, Result<(PathBuf, Keep), VisionError>> { + Box::pin(Vision::combine(self, images)) + } +} diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index a3613c96..e3c86a84 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -11,7 +11,12 @@ use axum::{ use serde::Serialize; use tokio::sync::{RwLock, mpsc}; +use crate::ports::{ + SharedClock, SharedEngine, SharedResponseStore, SharedToolHub, SharedVisionEncoder, +}; + use crate::{ + adapters::ChannelEngine, codec::TextCodec, responses, worker::{GenerationCommand, WorkerState, WorkerStatus}, @@ -27,8 +32,12 @@ pub struct AppState { /// With a worker pool, the status of every member (the first is `worker`); empty otherwise. pub pool: Vec>>, pub tokenizer: Option>, - pub generation: Option>, - pub response_history: Arc>, + /// The engine the generation routes submit to; `None` until a worker is configured. + pub engine: Option, + /// Stored Responses (`store`, `previous_response_id`, `GET/DELETE /v1/responses/{id}`). + pub responses: SharedResponseStore, + /// Wall and monotonic time: queue deadlines, uptime, response timestamps. + pub clock: SharedClock, pub settings: Arc, /// Other names of the model (`aliases` in the config), answered like the model's own. pub aliases: Arc>, @@ -42,9 +51,9 @@ pub struct AppState { /// Source of the model's chat template, served by `/props`. pub chat_template: Option>, /// The MCP servers configured for the operator (`GET /mcp`). - pub mcp: Option>, + pub mcp: Option, /// The resident image encoder (`vision` in the config); `None`: this server cannot read images. - pub vision: Option>, + pub vision: Option, /// The engine's prefix-cache summary for a pool router (`GET /v1/status`, `POST /v1/prefix_match`). pub prefix_cache: Arc, /// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory` (`docs/memory-safety.md`). @@ -53,6 +62,15 @@ pub struct AppState { pub monitor: Arc, } +impl AppState { + /// Give the state a command channel of `capacity` places as its engine; the worker side reads the receiver. + pub fn attach_engine(&mut self, capacity: usize) -> mpsc::Receiver { + let (engine, receiver) = ChannelEngine::channel(capacity, self.clock.clone()); + self.engine = Some(engine); + receiver + } +} + #[derive(Serialize)] struct HealthResponse { status: &'static str, diff --git a/control-plane/src/app/impl_default_for_appstate.rs b/control-plane/src/app/impl_default_for_appstate.rs index 407c8e3c..34aefc2f 100644 --- a/control-plane/src/app/impl_default_for_appstate.rs +++ b/control-plane/src/app/impl_default_for_appstate.rs @@ -5,6 +5,7 @@ use super::*; impl Default for AppState { fn default() -> Self { + let clock = crate::adapters::SystemClock::shared(); Self { queue_timeout: None, lifecycle: Default::default(), @@ -13,14 +14,17 @@ impl Default for AppState { worker: Arc::new(RwLock::new(WorkerStatus::default())), pool: Vec::new(), tokenizer: None, - generation: None, - response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())), + engine: None, + responses: responses::HistoryResponseStore::shared( + responses::ResponseHistory::default(), + ), + clock: clock.clone(), settings: Arc::new(crate::settings::Settings::default()), aliases: Arc::new(Vec::new()), cors: Arc::new(Default::default()), trusted_origins: Arc::new(Vec::new()), control: None, - started_at: std::time::SystemTime::now(), + started_at: clock.system_time(), chat_template: None, mcp: None, vision: None, diff --git a/control-plane/src/app/metrics_document.rs b/control-plane/src/app/metrics_document.rs index 4a0c4861..cc4eb446 100644 --- a/control-plane/src/app/metrics_document.rs +++ b/control-plane/src/app/metrics_document.rs @@ -10,11 +10,8 @@ pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_jso let worker = *state.worker.read().await; let generation = worker.metrics; let lifecycle = state.lifecycle.snapshot(); - let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity); - let queue_used = state - .generation - .as_ref() - .map(|sender| sender.max_capacity() - sender.capacity()); + let queue_capacity = state.engine.as_ref().map(|engine| engine.queue_capacity()); + let queue_used = state.engine.as_ref().map(|engine| engine.queue_used()); let memory = state.memory.status(); let (hardware, hardware_static, telemetry, history) = state.memory.hardware(); let busy = generation.active_since.is_some(); @@ -82,16 +79,23 @@ pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_jso "requests": requests, "requests_kept": requests_kept, "totals": totals, - "api_uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()), + "api_uptime_s": uptime_s(state), "supervisor": supervisor_block(), "hardware": hardware, "hardware_static": hardware_static, "history": history, "telemetry": telemetry, - "time": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()), + "time": state.clock.unix_time().as_secs_f64(), }) } +/// Seconds since the API started, on the state's clock. +pub(crate) fn uptime_s(state: &AppState) -> u64 { + let now = state.clock.system_time(); + now.duration_since(state.started_at) + .map_or(0, |d| d.as_secs()) +} + /// The supervisor's own account (`LELEKA_STATUS_FILE`, set by `leleka run`): restarts and uptime of the service. `null` when this /// process was not started by a supervisor, or the file cannot be read. pub(super) fn supervisor_block() -> serde_json::Value { @@ -120,7 +124,7 @@ pub(super) async fn ready(State(state): State) -> (StatusCode, Json) -> Json = std::result::Result>; +type Result = std::result::Result; #[derive(Deserialize)] #[serde(deny_unknown_fields)] diff --git a/control-plane/src/doctor.rs b/control-plane/src/doctor.rs index 94f41414..02f258e8 100644 --- a/control-plane/src/doctor.rs +++ b/control-plane/src/doctor.rs @@ -1,6 +1,6 @@ //! Read-only Linux driver-version checks for the explicit CUDA 13.0 GA profile. use serde::{Deserialize, Serialize}; -use std::{error::Error, fs, process::Stdio, time::Duration}; +use std::{fs, process::Stdio, time::Duration}; use tokio::{io::AsyncReadExt, process::Command, time::timeout}; const MIN_DRIVER: DriverVersion = DriverVersion(580, 65, 6); @@ -15,7 +15,7 @@ pub enum GpuRequirement { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct DriverVersion(u32, u32, u32); -pub async fn report() -> Result<(), Box> { +pub async fn report() -> Result<(), crate::BoxError> { println!( "platform: {} {}", std::env::consts::OS, @@ -29,7 +29,7 @@ pub async fn report() -> Result<(), Box> { Ok(()) } -pub async fn check(_requirement: GpuRequirement) -> Result> { +pub async fn check(_requirement: GpuRequirement) -> Result { if !cfg!(target_os = "linux") { return Err("cuda-13.0-linux requires Linux; select a compatible host/profile".into()); } @@ -46,7 +46,7 @@ pub async fn check(_requirement: GpuRequirement) -> Result Result> { +async fn probe() -> Result { let mut child = Command::new("nvidia-smi") .args(["--query-gpu=driver_version", "--format=csv,noheader"]) .stdin(Stdio::null()) diff --git a/control-plane/src/embedded_engine.rs b/control-plane/src/embedded_engine.rs index 14c6b91e..ebf2c8f8 100644 --- a/control-plane/src/embedded_engine.rs +++ b/control-plane/src/embedded_engine.rs @@ -1,5 +1,5 @@ //! Opt-in packaged worker. The host still supplies the ELF's shared libraries. -use std::{error::Error, ffi::OsStr, fs::File, path::PathBuf}; +use std::{ffi::OsStr, fs::File, path::PathBuf}; mod payload { include!(concat!(env!("OUT_DIR"), "/embedded-engine.rs")); @@ -25,7 +25,7 @@ pub struct EmbeddedEngine { pub executable: PathBuf, } -pub fn resolve(executable: &OsStr) -> Result, Box> { +pub fn resolve(executable: &OsStr) -> Result, crate::BoxError> { if executable != OsStr::new("@embedded") { return Ok(None); } @@ -39,7 +39,7 @@ pub fn resolve(executable: &OsStr) -> Result, Box Result<(), Box> { +pub fn help() -> Result<(), crate::BoxError> { let engine = resolve(OsStr::new("@embedded"))?.ok_or("no embedded engine")?; let status = std::process::Command::new(&engine.executable) .arg("--help") @@ -52,12 +52,12 @@ pub fn help() -> Result<(), Box> { } #[cfg(not(target_os = "linux"))] -fn materialize(_: &[u8]) -> Result> { +fn materialize(_: &[u8]) -> Result { Err("embedded worker execution requires Linux".into()) } #[cfg(target_os = "linux")] -fn materialize(bytes: &[u8]) -> Result> { +fn materialize(bytes: &[u8]) -> Result { use std::{ io::Write, os::fd::{AsRawFd, FromRawFd}, diff --git a/control-plane/src/engine_probe.rs b/control-plane/src/engine_probe.rs index 9c2a6006..6d7a3ef4 100644 --- a/control-plane/src/engine_probe.rs +++ b/control-plane/src/engine_probe.rs @@ -1,8 +1,8 @@ //! Explicit loader probe for an operator-trusted engine with a side-effect-free --help. -use std::{error::Error, ffi::OsStr, process::Stdio, time::Duration}; +use std::{ffi::OsStr, process::Stdio, time::Duration}; use tokio::{process::Command, time::timeout}; -pub async fn check(executable: &OsStr) -> Result<(), Box> { +pub async fn check(executable: &OsStr) -> Result<(), crate::BoxError> { // Keep the memfd alive until the help process has exited. Serving may have // already resolved the payload and keeps its own lifetime guard. let embedded = crate::embedded_engine::resolve(executable)?; diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index 65d47f94..f6b0f0cd 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -22,6 +22,10 @@ macro_rules! wlog { }}; } +/// The boxed error the command-line and offline-tool functions return. +pub type BoxError = Box; + +pub mod adapters; pub mod app; pub mod asset_bundle; pub mod auth; @@ -66,6 +70,7 @@ pub mod mtp_pack; pub mod native_model; pub mod native_pack; pub mod pool; +pub mod ports; pub mod prefix_view; pub mod preflight; pub mod prepare_preview; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 46f8333f..85883456 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -917,7 +917,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box) -> Result<(), Box) -> Result<(), Box) -> Result<(), Box = match config.worker { None => Vec::new(), Some(mut main) if extra_workers.is_empty() => { - main.vision = state.vision.clone(); - let (sender, receiver) = mpsc::channel(16); + main.vision = vision_process.clone(); + let receiver = state.attach_engine(16); let (control_sender, control_receiver) = mpsc::channel(16); - state.generation = Some(sender); state.control = Some(control_sender); vec![tokio::spawn(worker::run_supervised( main, @@ -1046,8 +1047,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box) -> Result<(), Box) -> Result<(), Box = std::result::Result>; +type Result = std::result::Result; const FETCH_ATTEMPTS: usize = 4; #[derive(Deserialize)] diff --git a/control-plane/src/model_pipeline.rs b/control-plane/src/model_pipeline.rs index 1822c559..67f6ed75 100644 --- a/control-plane/src/model_pipeline.rs +++ b/control-plane/src/model_pipeline.rs @@ -2,7 +2,6 @@ //! experimental until real-model quality and Linux GPU loading are verified. use std::{ - error::Error, fs, io, path::{Component, Path}, }; @@ -19,7 +18,7 @@ pub async fn ensure_sharded_preview( source_dir: &Path, archive: &Path, levels: u8, -) -> Result> { +) -> Result { if !(1..=8).contains(&levels) { return Err("sharded preview requires 1..=8 KAR levels".into()); } @@ -64,7 +63,7 @@ pub async fn ensure_sharded_streamed( source_dir: &Path, archive: &Path, levels: u8, -) -> Result> { +) -> Result { ensure_sharded_streamed_with_policy(manifest, source_dir, archive, levels, None).await } @@ -74,7 +73,7 @@ pub async fn ensure_sharded_streamed_ple( archive: &Path, levels: u8, ple_part_elements: u64, -) -> Result> { +) -> Result { ensure_sharded_streamed_with_policy( manifest, source_dir, @@ -91,7 +90,7 @@ async fn ensure_sharded_streamed_with_policy( archive: &Path, levels: u8, ple_part_elements: Option, -) -> Result> { +) -> Result { if !(1..=8).contains(&levels) { return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); } @@ -144,7 +143,7 @@ fn preflight_existing_shards( source_dir: &Path, archive: &Path, levels: u8, -) -> Result<(), Box> { +) -> Result<(), crate::BoxError> { match fs::symlink_metadata(archive) { Ok(_) => return Ok(()), // Reusing an archive needs no new payload space. Err(error) if error.kind() == io::ErrorKind::NotFound => {} diff --git a/control-plane/src/models_api.rs b/control-plane/src/models_api.rs index 60e357c9..87b1cf4c 100644 --- a/control-plane/src/models_api.rs +++ b/control-plane/src/models_api.rs @@ -96,13 +96,14 @@ pub async fn retrieve( #[cfg(test)] mod tests { use super::*; + use crate::adapters::ChannelEngine; #[tokio::test] async fn discovery_during_worker_outage_and_drain_never_schedules_generation() { let (sender, mut receiver) = tokio::sync::mpsc::channel(1); let state = AppState { model: Some("org/model : v1".into()), - generation: Some(sender), + engine: Some(ChannelEngine::shared(sender)), ..Default::default() }; state.lifecycle.set_draining(true); diff --git a/control-plane/src/mtp_fetch.rs b/control-plane/src/mtp_fetch.rs index 40622a61..68f692b0 100644 --- a/control-plane/src/mtp_fetch.rs +++ b/control-plane/src/mtp_fetch.rs @@ -15,7 +15,6 @@ //! SHA-256 table below. use std::{ collections::{BTreeMap, BTreeSet}, - error::Error, fs::{self, File, OpenOptions}, io::{Read, Write}, path::{Path, PathBuf}, @@ -30,7 +29,7 @@ use serde::Serialize; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; -type Result = std::result::Result>; +type Result = std::result::Result; /// A fixed commit of the checkpoint (its `sha` on 2026-09-30), so every install reads the same tensors; /// `STRATA_MTP_REVISION` overrides it (e.g. `main`). diff --git a/control-plane/src/native_model.rs b/control-plane/src/native_model.rs index 7d923bff..34de1262 100644 --- a/control-plane/src/native_model.rs +++ b/control-plane/src/native_model.rs @@ -7,13 +7,12 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ collections::BTreeMap, - error::Error, fs::{self, File, OpenOptions}, io::Read, path::{Path, PathBuf}, }; -type Result = std::result::Result>; +type Result = std::result::Result; const FILES: &[&str] = &[ "dense.bin", "index.txt", diff --git a/control-plane/src/native_pack.rs b/control-plane/src/native_pack.rs index 560072f9..2dc86e6a 100644 --- a/control-plane/src/native_pack.rs +++ b/control-plane/src/native_pack.rs @@ -2,7 +2,6 @@ //! shards; float conversions are exact unless `--compat-bf16` is given. No runtime Python. use std::{ collections::{BTreeMap, HashSet}, - error::Error, fs::{self, File}, io::{Read, Seek, SeekFrom, Write}, path::{Path, PathBuf}, @@ -13,7 +12,7 @@ use sha2::{Digest, Sha256}; use crate::{gguf, gguf_f32_stream, kar_codec, model, tokenizer, tokenizer_assets}; -type Result = std::result::Result>; +type Result = std::result::Result; struct Shard { path: PathBuf, diff --git a/control-plane/src/ports.rs b/control-plane/src/ports.rs new file mode 100644 index 00000000..3e75f357 --- /dev/null +++ b/control-plane/src/ports.rs @@ -0,0 +1,29 @@ +//! Ports of the HTTP/Responses gateway (STRA-338 S16). +//! +//! A port is a small trait the gateway domain (the Responses and server handlers) talks to. The adapters behind them +//! are the channel to the engine worker, the in-memory/disk response history, the system clock, the MCP servers +//! and the resident image encoder. `AppState` holds `Arc`, never a concrete adapter; `main` is the only +//! place that picks adapters. `fakes` has an in-memory adapter for each port, for tests that need no process, no +//! socket and no disk. +//! +//! The ports are called once per request (`EngineClient::submit`, `ResponseStore::*`, `VisionEncoder::*`, +//! `ToolHub::call`) or once per process. None of them is called per token or per stream event: the streaming loops +//! read the plain `mpsc` channel of the command and never go through a trait object. +//! +//! `docs/architecture/gateway-ports.md` has the port list and the dependency picture. + +pub mod clock; +pub mod engine; +pub mod fakes; +pub mod response_store; +pub mod tool_hub; +pub mod vision; + +/// What an object-safe async method returns: a boxed future that may borrow from `self` and its arguments. +pub type BoxFuture<'a, T> = std::pin::Pin + Send + 'a>>; + +pub use clock::{Clock, SharedClock}; +pub use engine::{EngineClient, SharedEngine}; +pub use response_store::{ResponseStore, SharedResponseStore}; +pub use tool_hub::{SharedToolHub, ToolHub}; +pub use vision::{SharedVisionEncoder, VisionEncoder}; diff --git a/control-plane/src/ports/clock.rs b/control-plane/src/ports/clock.rs new file mode 100644 index 00000000..01e37b5d --- /dev/null +++ b/control-plane/src/ports/clock.rs @@ -0,0 +1,24 @@ +//! The gateway's source of time, injectable so queue deadlines, uptime and response timestamps can be tested +//! without sleeping. + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::time::Instant; + +/// What `AppState` and the adapters hold. +pub type SharedClock = std::sync::Arc; + +pub trait Clock: Send + Sync { + /// Monotonic time (queue deadlines, activity stamps). It is tokio's `Instant`, so a test that pauses the tokio + /// clock moves this one too. + fn now(&self) -> Instant; + + /// Wall-clock time (response `created_at`, `started_at`, uptime). + fn system_time(&self) -> SystemTime; + + /// The wall clock as the time since the Unix epoch; zero for a clock set before it. + fn unix_time(&self) -> Duration { + self.system_time() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + } +} diff --git a/control-plane/src/ports/engine.rs b/control-plane/src/ports/engine.rs new file mode 100644 index 00000000..cfc62007 --- /dev/null +++ b/control-plane/src/ports/engine.rs @@ -0,0 +1,25 @@ +//! The gateway's view of the engine: submit one generation, learn the size of the queue in front of it. + +use std::time::Duration; + +use super::BoxFuture; +use crate::{queue::Error, worker::GenerationCommand}; + +/// What `AppState` holds. +pub type SharedEngine = std::sync::Arc; + +pub trait EngineClient: Send + Sync { + /// Hand one generation to the engine. `Ok` means the engine side took it (and, with a `budget`, claimed it before + /// the queue deadline); the events then arrive through `command.result`. `Err` says why it was not taken. + fn submit( + &self, + command: GenerationCommand, + budget: Option, + ) -> BoxFuture<'_, Result<(), Error>>; + + /// How many commands may wait in front of the engine (`/metrics`, `queue_capacity`). + fn queue_capacity(&self) -> usize; + + /// How many of those places are taken now (`/metrics`, `queue_used`). + fn queue_used(&self) -> usize; +} diff --git a/control-plane/src/ports/fakes.rs b/control-plane/src/ports/fakes.rs new file mode 100644 index 00000000..31b445bc --- /dev/null +++ b/control-plane/src/ports/fakes.rs @@ -0,0 +1,13 @@ +//! In-memory adapters of the gateway ports, for tests: no process, no socket, no disk, no real time. + +mod clock; +mod engine; +mod store; +mod tool_hub; +mod vision; + +pub use clock::ManualClock; +pub use engine::{Script, ScriptedEngine}; +pub use store::MemoryResponseStore; +pub use tool_hub::FakeToolHub; +pub use vision::FakeVisionEncoder; diff --git a/control-plane/src/ports/fakes/clock.rs b/control-plane/src/ports/fakes/clock.rs new file mode 100644 index 00000000..2a9da3fe --- /dev/null +++ b/control-plane/src/ports/fakes/clock.rs @@ -0,0 +1,44 @@ +use std::{ + sync::{Arc, Mutex}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use tokio::time::Instant; + +use crate::ports::Clock; + +/// A clock that moves only when the test says so. +pub struct ManualClock { + base: Instant, + epoch: SystemTime, + elapsed: Mutex, +} + +impl ManualClock { + /// Starts at `unix_secs` seconds after the epoch. + pub fn new(unix_secs: u64) -> Arc { + Arc::new(Self { + base: Instant::now(), + epoch: UNIX_EPOCH + Duration::from_secs(unix_secs), + elapsed: Mutex::new(Duration::ZERO), + }) + } + + pub fn advance(&self, by: Duration) { + *self.elapsed.lock().unwrap() += by; + } + + fn elapsed(&self) -> Duration { + *self.elapsed.lock().unwrap() + } +} + +impl Clock for ManualClock { + fn now(&self) -> Instant { + self.base + self.elapsed() + } + + fn system_time(&self) -> SystemTime { + self.epoch + self.elapsed() + } +} diff --git a/control-plane/src/ports/fakes/engine.rs b/control-plane/src/ports/fakes/engine.rs new file mode 100644 index 00000000..1df3cf2d --- /dev/null +++ b/control-plane/src/ports/fakes/engine.rs @@ -0,0 +1,131 @@ +use std::{ + collections::VecDeque, + sync::{Arc, Mutex}, + time::Duration, +}; + +use crate::{ + ports::{BoxFuture, EngineClient}, + queue::Error, + wire::{Done, Event, Finish, Generate}, + worker::{GenerationCommand, GenerationResult}, +}; + +/// What the fake engine does with the next submitted command. +pub enum Script { + /// Answer with these events (the last one should be `Event::Done`). + Events(Vec), + /// Answer with a generation error (the 502 `generation_failed` path). + Fail(String), + /// Do not take the command: the queue refused it. + Refuse(Error), +} + +impl Script { + /// The tokens, then a `Done` that stopped normally. + pub fn tokens(tokens: &[u32]) -> Self { + let mut events: Vec = tokens.iter().copied().map(Event::Token).collect(); + events.push(Event::Done(Done { + generated: tokens.len() as u64, + prompt_tokens: 0, + prompt_ms: 0.0, + decode_ms: 0.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + })); + Self::Events(events) + } +} + +/// An engine that answers from a script and remembers what it was asked. Commands beyond the script get a bare +/// `Stop`. +pub struct ScriptedEngine { + scripts: Mutex>, + seen: Mutex>, + budgets: Mutex>>, + capacity: usize, +} + +impl ScriptedEngine { + pub fn new(scripts: Vec