STRA-338: integrate the gateway track (S16, S7, S21) into the hexagonal base

This commit is contained in:
Pavlo Ratushnyi
2026-11-05 21:50:40 +01:00
142 changed files with 6996 additions and 4471 deletions
Generated
+11
View File
@@ -1320,6 +1320,16 @@ dependencies = [
"serde_json",
]
[[package]]
name = "leleka-gateway-domain"
version = "0.1.0"
dependencies = [
"leleka-sampler-ref",
"leleka-tokenizer",
"serde",
"serde_json",
]
[[package]]
name = "leleka-gateway-text"
version = "0.1.0"
@@ -2793,6 +2803,7 @@ dependencies = [
"http-body-util",
"jsonschema",
"leleka-backend-api",
"leleka-gateway-domain",
"leleka-gateway-text",
"leleka-gguf",
"leleka-harmony",
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
[workspace.package]
edition = "2024"
+10 -15
View File
@@ -5,22 +5,16 @@
"forbidden-dep leleka-memory windows-sys"
],
"oversize": {
"control-plane/examples/cp_replay.rs": 946,
"control-plane/src/config/impl_config/impl_config_2_2.rs": 434,
"control-plane/examples/cp_replay.rs": 953,
"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/prepare_preview/tests.rs": 808,
"control-plane/src/prometheus.rs": 441,
"control-plane/src/responses/tests.rs": 2961,
"control-plane/src/service_install.rs": 436,
"control-plane/src/vision.rs": 402,
"control-plane/src/worker.rs": 1271,
"control-plane/tests/backend_worker_http.rs": 1832,
"control-plane/tests/mcp_hub.rs": 444,
"control-plane/tests/memory_gate_http.rs": 464,
"control-plane/src/responses/tests.rs": 2972,
"control-plane/tests/backend_worker_http.rs": 1846,
"control-plane/tests/mcp_hub.rs": 447,
"control-plane/tests/memory_gate_http.rs": 471,
"control-plane/tests/tool_corpus.rs": 464,
"control-plane/tests/vision_http.rs": 602,
"control-plane/tests/vision_http.rs": 608,
"crates/backend-api/src/lib.rs": 756,
"crates/context/tests/rope_plan_golden.rs": 412,
"crates/cpu-kernels/src/lib.rs": 464,
@@ -126,7 +120,7 @@
"desktop-core/src/bin/leleka-inference.rs": 1487,
"desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs": 463,
"desktop-core/src/runtime_rpc/tests.rs": 628,
"desktop-core/tests/api_over_runtime.rs": 638,
"desktop-core/tests/api_over_runtime.rs": 644,
"desktop-core/tests/gateway.rs": 403,
"desktop-core/tests/managed_worker.rs": 500,
"desktop-core/tests/native_tools_retry_sdet.rs": 552,
@@ -139,6 +133,7 @@
"dyn-trait:leleka-cuda-driver": 51,
"dyn-trait:leleka-deploy": 17,
"dyn-trait:leleka-experimental-ref": 3,
"dyn-trait:leleka-gateway-domain": 5,
"dyn-trait:leleka-gptoss": 10,
"dyn-trait:leleka-gptoss-igpu": 4,
"dyn-trait:leleka-gptoss-npu": 4,
@@ -147,7 +142,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": 16,
"dyn-trait:strata-desktop-core": 2,
"env-read:leleka-cpu-kernels": 1,
"env-read:leleka-cpu-worker": 2,
@@ -184,7 +179,7 @@
"instant-now:leleka-native-cpu-expert": 30,
"instant-now:leleka-npu-service": 5,
"instant-now:leleka-runtime": 79,
"instant-now:strata-control": 37,
"instant-now:strata-control": 31,
"instant-now:strata-desktop-core": 15,
"path-include:leleka-cuda-driver": 115,
"path-include:leleka-model-format": 12,
+3 -3
View File
@@ -1,8 +1,8 @@
{
"_comment": "Policy read by scripts/check-architecture.py (STRA-338 ADR). Layers are ordered low to high; a normal dependency must point to the same or a lower layer. L2 (core) is reserved: it is empty until the engine/gateway domain crates are extracted (steps S19, S21). Every workspace package appears in exactly one layer.",
"_comment": "Policy read by scripts/check-architecture.py (STRA-338 ADR). Layers are ordered low to high; a normal dependency must point to the same or a lower layer. L2 (core) holds the extracted domain crates: leleka-gateway-domain (S21); the engine domain crates follow (S19). Every workspace package appears in exactly one layer.",
"max_lines": 400,
"adapter_layer": "L3",
"pure_layers": ["L0", "L1"],
"pure_layers": ["L0", "L1", "L2"],
"forbidden_in_pure": ["tokio", "axum", "tonic", "tonic-prost", "reqwest", "hyper", "libc", "rustix", "windows-sys", "sysinfo", "wgpu"],
"layers": {
"L0": ["leleka-backend-api", "leleka-worker-protocol"],
@@ -11,7 +11,7 @@
"leleka-tokenizer", "leleka-gguf", "leleka-kar-codec", "leleka-experimental-ref", "leleka-cpu-sys", "leleka-cpu-kernels",
"leleka-shm", "leleka-openvino", "leleka-memory", "leleka-gateway-text"
],
"L2": [],
"L2": ["leleka-gateway-domain"],
"L3": [
"leleka-libc-shim", "leleka-model-format", "leleka-cuda-driver", "leleka-native-cpu-expert", "leleka-gptoss", "leleka-igpu",
"leleka-gptoss-igpu", "leleka-gptoss-npu", "leleka-npu-service", "leleka-cpu-worker", "leleka-igpu-worker", "leleka-npu-worker",
+1
View File
@@ -15,6 +15,7 @@ axum = "0.8"
futures-core = "0.3"
hex = "0.4"
leleka-gguf = { path = "../crates/gguf" }
leleka-gateway-domain = { path = "../crates/gateway-domain" }
leleka-gateway-text = { path = "../crates/gateway-text" }
leleka-worker-protocol = { path = "../crates/worker-protocol" }
leleka-obs = { path = "../crates/obs" }
+14 -7
View File
@@ -34,6 +34,7 @@ use std::{
},
time::{Duration, Instant},
};
use strata_control::app::{EngineLink, ModelView};
use leleka_backend_api::{
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent,
@@ -277,13 +278,19 @@ where
control_rx,
));
let state = AppState {
model: Some("fixture".into()),
worker: status.clone(),
tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared(
tokenizer.clone(),
))),
generation: Some(requests),
control: Some(control),
engine: EngineLink {
worker: status.clone(),
client: Some(strata_control::adapters::ChannelEngine::shared(requests)),
control: Some(control),
..Default::default()
},
model: ModelView {
name: Some("fixture".into()),
tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared(
tokenizer.clone(),
))),
..Default::default()
},
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+17
View File
@@ -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;
@@ -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<GenerationCommand>,
clock: SharedClock,
}
impl ChannelEngine {
pub fn new(sender: mpsc::Sender<GenerationCommand>, 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<GenerationCommand>) {
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<GenerationCommand>) -> SharedEngine {
Arc::new(Self::new(sender, SystemClock::shared()))
}
}
impl EngineClient for ChannelEngine {
fn submit(
&self,
command: GenerationCommand,
budget: Option<Duration>,
) -> 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));
}
}
@@ -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<Value>> {
Box::pin(Hub::template_tools(self, exclude))
}
fn call<'a>(
&'a self,
name: &'a str,
arguments: Value,
cancel: Option<Cancel>,
) -> BoxFuture<'a, Result<CallOutput, McpError>> {
Box::pin(Hub::call(self, name, arguments, cancel))
}
fn close(&self) -> BoxFuture<'_, ()> {
Box::pin(Hub::close(self))
}
}
@@ -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()
}
}
@@ -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<Vec<Encoded>, 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))
}
}
+11 -43
View File
@@ -1,5 +1,3 @@
use std::sync::Arc;
use axum::{
Json, Router,
extract::{DefaultBodyLimit, RawQuery, State},
@@ -9,50 +7,12 @@ use axum::{
routing::{get, post},
};
use serde::Serialize;
use tokio::sync::{RwLock, mpsc};
use crate::{
codec::TextCodec,
responses,
worker::{GenerationCommand, WorkerState, WorkerStatus},
worker::{WorkerState, WorkerStatus},
};
#[derive(Clone)]
pub struct AppState {
pub queue_timeout: Option<std::time::Duration>,
pub lifecycle: crate::lifecycle::Lifecycle,
pub api_key: Option<Arc<crate::auth::ApiKey>>,
pub model: Option<String>,
pub worker: Arc<RwLock<WorkerStatus>>,
/// With a worker pool, the status of every member (the first is `worker`); empty otherwise.
pub pool: Vec<Arc<RwLock<WorkerStatus>>>,
pub tokenizer: Option<Arc<dyn TextCodec>>,
pub generation: Option<mpsc::Sender<GenerationCommand>>,
pub response_history: Arc<RwLock<responses::ResponseHistory>>,
pub settings: Arc<crate::settings::Settings>,
/// Other names of the model (`aliases` in the config), answered like the model's own.
pub aliases: Arc<Vec<String>>,
/// Browser pages of these origins may call `/v1/*`.
pub cors: Arc<leleka_serving_policy::cors::Cors>,
/// Origins that count as this server's own page for `/settings` and `/v1/load|unload`.
pub trusted_origins: Arc<Vec<String>>,
/// Administrative channel to the worker supervisor (load/unload); `None` without a worker.
pub control: Option<mpsc::Sender<crate::worker::Control>>,
pub started_at: std::time::SystemTime,
/// Source of the model's chat template, served by `/props`.
pub chat_template: Option<Arc<str>>,
/// The MCP servers configured for the operator (`GET /mcp`).
pub mcp: Option<Arc<crate::mcp::Hub>>,
/// The resident image encoder (`vision` in the config); `None`: this server cannot read images.
pub vision: Option<Arc<crate::vision::Vision>>,
/// The engine's prefix-cache summary for a pool router (`GET /v1/status`, `POST /v1/prefix_match`).
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory` (`docs/memory-safety.md`).
pub memory: Arc<crate::memory_view::MemoryView>,
/// The API request monitor (`api_monitor` in the config; off by default): `GET /api/requests`.
pub monitor: Arc<crate::request_monitor::RequestMonitor>,
}
#[derive(Serialize)]
struct HealthResponse {
status: &'static str,
@@ -75,9 +35,17 @@ const RECENT_REQUESTS: usize = 12;
#[cfg(test)]
mod tests;
mod impl_default_for_appstate;
mod state;
pub use state::{AppState, EngineLink, HttpPolicy, ModelView, Services};
mod routes;
#[allow(unused_imports)]
pub use impl_default_for_appstate::*;
pub use routes::*;
mod admin_routes;
#[allow(unused_imports)]
pub use admin_routes::*;
mod readiness;
#[allow(unused_imports)]
pub use readiness::*;
mod metrics_document;
#[allow(unused_imports)]
pub use metrics_document::*;
+89
View File
@@ -0,0 +1,89 @@
//! Liveness, lifecycle (drain/resume) and `GET /metrics`.
#[allow(unused_imports)]
use super::*;
pub(super) async fn health() -> Json<HealthResponse> {
Json(HealthResponse { status: "ok" })
}
pub(super) async fn lifecycle_status(State(state): State<AppState>) -> Json<serde_json::Value> {
let worker = *state.engine.worker.read().await;
let lifecycle = state.lifecycle.snapshot();
let drained = lifecycle.draining
&& lifecycle.requests_in_flight == 0
&& lifecycle.generation_jobs == 0
&& worker.metrics.active_since.is_none()
&& matches!(
worker.state,
WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded
);
Json(
serde_json::json!({"service":"strata-control", "server_pid":std::process::id(), "model":state.model.name,
"draining":lifecycle.draining,
"shutting_down":lifecycle.shutting_down,
"max_in_flight_requests":lifecycle.max_in_flight_requests,
"available_request_slots":lifecycle.max_in_flight_requests.saturating_sub(lifecycle.requests_in_flight),
"requests_in_flight":lifecycle.requests_in_flight, "generation_jobs":lifecycle.generation_jobs,
"drained":drained, "worker":worker.state}),
)
}
pub(super) fn lifecycle_precondition(headers: &HeaderMap) -> Option<Response> {
let mut values = headers.get_all("x-strata-expected-pid").iter();
let value = values.next()?;
let pid = value
.to_str()
.ok()
.filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
.and_then(|s| s.parse::<u32>().ok())
.filter(|n| *n > 0);
if values.next().is_some() || pid.is_none() {
return Some((StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":{"code":"invalid_expected_pid","message":"expected PID must be one positive integer"}}))).into_response());
}
if pid != Some(std::process::id()) {
return Some((StatusCode::CONFLICT, Json(serde_json::json!({"error":{"code":"process_identity_changed","message":"native process no longer matches expected PID; admission unchanged"}}))).into_response());
}
None
}
pub(super) async fn drain(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(true);
lifecycle_status(State(state)).await.into_response()
}
pub(super) async fn resume(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(false);
lifecycle_status(State(state)).await.into_response()
}
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept` that asks
/// for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept generation, not the last 12.
pub(super) async fn metrics(
State(state): State<AppState>,
RawQuery(query): RawQuery,
headers: HeaderMap,
) -> Response {
let accept = headers
.get(axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok());
let all = query
.as_deref()
.is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
);
return response;
}
Json(document).into_response()
}
@@ -1,236 +0,0 @@
//! Moved out of the parent module by STRA-338: impl Default_for_AppState, fn router, fn health, fn lifecycle_status, fn lifecycle_precondition, fn drain ....
#[allow(unused_imports)]
use super::*;
impl Default for AppState {
fn default() -> Self {
Self {
queue_timeout: None,
lifecycle: Default::default(),
api_key: None,
model: None,
worker: Arc::new(RwLock::new(WorkerStatus::default())),
pool: Vec::new(),
tokenizer: None,
generation: None,
response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())),
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(),
chat_template: None,
mcp: None,
vision: None,
prefix_cache: Arc::new(Default::default()),
memory: Arc::new(Default::default()),
monitor: Arc::new(Default::default()),
}
}
}
pub fn router(state: AppState) -> Router {
let observe = crate::request_log::Observe {
model: state.model.clone(),
memory: state.memory.clone(),
};
Router::new()
.route("/health", get(health))
.route("/ready", get(ready))
.route("/status", get(status))
.route("/metrics", get(metrics))
.route("/api/health", get(crate::server_api::api_health))
.route("/props", get(crate::server_api::props))
.route("/slots", get(crate::server_api::slots))
.route("/v1/status", get(crate::server_api::v1_status))
.route("/v1/prefix_match", post(crate::server_api::v1_prefix_match))
.route("/v1/reconfigure", post(crate::server_api::v1_reconfigure))
.route("/mcp", get(crate::server_api::mcp_status))
.route(
"/settings",
get(crate::server_api::settings_get).post(crate::server_api::settings_post),
)
.route("/load", post(crate::server_api::load_post))
.route("/unload", post(crate::server_api::unload_post))
.route("/v1/load", post(crate::server_api::v1_load))
.route("/v1/unload", post(crate::server_api::v1_unload))
.route("/models", get(crate::models_api::list))
.route("/v1/models", get(crate::models_api::list))
.route("/v1/models/{id}", get(crate::models_api::retrieve))
.route(
"/v1/responses",
post(responses::create_route)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/responses/input_tokens",
post(responses::count_input_tokens).layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
)),
)
.route(
"/v1/chat/completions",
post(crate::chat::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/messages/count_tokens",
post(crate::messages::count_tokens)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol)),
)
.route(
"/v1/messages",
post(crate::messages::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol))
.layer(middleware::from_fn_with_state(
state.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route("/api/requests", get(crate::server_api::api_requests))
.route("/admin/lifecycle", get(lifecycle_status))
.route(
"/v1/responses/{id}",
get(responses::retrieve).delete(responses::delete),
)
.route(
"/v1/responses/{id}/input_items",
get(responses::input_items),
)
.route("/admin/drain", post(drain))
.route("/admin/resume", post(resume))
.fallback(crate::server_api::not_found)
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
state.api_key.clone(),
crate::auth::authorize,
))
// Outermost: a browser's credential-less preflight is answered before authentication.
.layer(middleware::from_fn_with_state(
state.cors.clone(),
crate::server_api::cors_layer,
))
.with_state(state)
}
pub(super) async fn health() -> Json<HealthResponse> {
Json(HealthResponse { status: "ok" })
}
pub(super) async fn lifecycle_status(State(state): State<AppState>) -> Json<serde_json::Value> {
let worker = *state.worker.read().await;
let lifecycle = state.lifecycle.snapshot();
let drained = lifecycle.draining
&& lifecycle.requests_in_flight == 0
&& lifecycle.generation_jobs == 0
&& worker.metrics.active_since.is_none()
&& matches!(
worker.state,
WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded
);
Json(
serde_json::json!({"service":"strata-control", "server_pid":std::process::id(), "model":state.model,
"draining":lifecycle.draining,
"shutting_down":lifecycle.shutting_down,
"max_in_flight_requests":lifecycle.max_in_flight_requests,
"available_request_slots":lifecycle.max_in_flight_requests.saturating_sub(lifecycle.requests_in_flight),
"requests_in_flight":lifecycle.requests_in_flight, "generation_jobs":lifecycle.generation_jobs,
"drained":drained, "worker":worker.state}),
)
}
pub(super) fn lifecycle_precondition(headers: &HeaderMap) -> Option<Response> {
let mut values = headers.get_all("x-strata-expected-pid").iter();
let value = values.next()?;
let pid = value
.to_str()
.ok()
.filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
.and_then(|s| s.parse::<u32>().ok())
.filter(|n| *n > 0);
if values.next().is_some() || pid.is_none() {
return Some((StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":{"code":"invalid_expected_pid","message":"expected PID must be one positive integer"}}))).into_response());
}
if pid != Some(std::process::id()) {
return Some((StatusCode::CONFLICT, Json(serde_json::json!({"error":{"code":"process_identity_changed","message":"native process no longer matches expected PID; admission unchanged"}}))).into_response());
}
None
}
pub(super) async fn drain(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(true);
lifecycle_status(State(state)).await.into_response()
}
pub(super) async fn resume(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(false);
lifecycle_status(State(state)).await.into_response()
}
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept` that asks
/// for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept generation, not the last 12.
pub(super) async fn metrics(
State(state): State<AppState>,
RawQuery(query): RawQuery,
headers: HeaderMap,
) -> Response {
let accept = headers
.get(axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok());
let all = query
.as_deref()
.is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
);
return response;
}
Json(document).into_response()
}
+27 -69
View File
@@ -1,4 +1,4 @@
//! Moved out of the parent module by STRA-338: fn metrics_document, fn supervisor_block, fn ready, fn status, fn pool_ready, fn status_body.
//! The `/metrics` document and the process uptime.
#[allow(unused_imports)]
use super::*;
@@ -7,16 +7,21 @@ use super::*;
/// (`engine`, `live`, `requests`, `requests_kept`, `totals`, `hardware`, `hardware_static`, `history`, `time`) and were added
/// beside the native ones, which are unchanged.
pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_json::Value {
let worker = *state.worker.read().await;
let worker = *state.engine.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
let queue_capacity = state
.engine
.client
.as_ref()
.map(|sender| sender.max_capacity() - sender.capacity());
let memory = state.memory.status();
let (hardware, hardware_static, telemetry, history) = state.memory.hardware();
.map(|engine| engine.queue_capacity());
let queue_used = state
.engine
.client
.as_ref()
.map(|engine| engine.queue_used());
let memory = state.model.memory.status();
let (hardware, hardware_static, telemetry, history) = state.model.memory.hardware();
let busy = generation.active_since.is_some();
let phase = telemetry["phase"].as_str();
let engine_state = if worker.state != WorkerState::Ready {
@@ -47,9 +52,9 @@ pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_jso
"prompt_read": null, "prompt_total": null, "max_tokens": null, "tok_s_window_s": null,
});
let engine = serde_json::json!({
"model": state.model, "max_context": worker.max_context.or(worker.known_max_context),
"images": state.vision.is_some(), "version": env!("CARGO_PKG_VERSION"),
"api_monitor": state.monitor.enabled(),
"model": state.model.name, "max_context": worker.max_context.or(worker.known_max_context),
"images": state.model.vision.is_some(), "version": env!("CARGO_PKG_VERSION"),
"api_monitor": state.services.monitor.enabled(),
"settings": telemetry["settings"].clone(),
});
let (requests, requests_kept, totals) = match generation.history {
@@ -63,7 +68,7 @@ pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_jso
serde_json::json!({
"schema_version": 1,
"scope": "control_plane_process",
"model": state.model,
"model": state.model.name,
"worker": worker.state,
"up": worker.state == WorkerState::Ready,
"active": busy,
@@ -72,7 +77,7 @@ pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_jso
"queue_used": queue_used,
"memory": {
"level": memory["gate"]["level"].clone(),
"gate_rejections": state.memory.gate_rejections(),
"gate_rejections": state.model.memory.gate_rejections(),
"available_bytes": memory["gate"]["available_bytes"].clone(),
},
"generation": generation,
@@ -82,16 +87,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.services.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.services.clock.system_time();
now.duration_since(state.services.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 {
@@ -114,57 +126,3 @@ pub(super) fn supervisor_block() -> serde_json::Value {
"last_restart_reason": status["last_restart_reason"],
})
}
pub(super) async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
let worker = *state.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.tokenizer.is_some()
&& state.generation.is_some()
&& !state.lifecycle.snapshot().draining;
let code = if inference_ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
code,
Json(status_body(worker, inference_ready, state.model)),
)
}
pub(super) async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
let worker = *state.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.tokenizer.is_some()
&& state.generation.is_some()
&& !state.lifecycle.snapshot().draining;
Json(status_body(worker, inference_ready, state.model))
}
/// Every member of a worker pool is ready (true without a pool).
pub(super) async fn pool_ready(state: &AppState) -> bool {
for member in &state.pool {
if member.read().await.state != WorkerState::Ready {
return false;
}
}
true
}
pub(super) fn status_body(
worker: WorkerStatus,
inference_ready: bool,
model: Option<String>,
) -> StatusResponse {
StatusResponse {
service: "strata-control",
server_pid: std::process::id(),
model,
version: env!("CARGO_PKG_VERSION"),
worker: worker.state,
ready: inference_ready,
max_context: worker.max_context,
}
}
+58
View File
@@ -0,0 +1,58 @@
//! `/ready` and `/status`: whether the engine can take a request, and the service status body.
#[allow(unused_imports)]
use super::*;
pub(super) async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
let worker = *state.engine.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.model.tokenizer.is_some()
&& state.engine.client.is_some()
&& !state.lifecycle.snapshot().draining;
let code = if inference_ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
code,
Json(status_body(worker, inference_ready, state.model.name)),
)
}
pub(super) async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
let worker = *state.engine.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
&& pool_ready(&state).await
&& state.model.tokenizer.is_some()
&& state.engine.client.is_some()
&& !state.lifecycle.snapshot().draining;
Json(status_body(worker, inference_ready, state.model.name))
}
/// Every member of a worker pool is ready (true without a pool).
pub(super) async fn pool_ready(state: &AppState) -> bool {
for member in &state.engine.pool {
if member.read().await.state != WorkerState::Ready {
return false;
}
}
true
}
pub(super) fn status_body(
worker: WorkerStatus,
inference_ready: bool,
model: Option<String>,
) -> StatusResponse {
StatusResponse {
service: "strata-control",
server_pid: std::process::id(),
model,
version: env!("CARGO_PKG_VERSION"),
worker: worker.state,
ready: inference_ready,
max_context: worker.max_context,
}
}
+123
View File
@@ -0,0 +1,123 @@
//! The route table: which handler serves which path, behind which middleware.
#[allow(unused_imports)]
use super::*;
pub fn router(state: AppState) -> Router {
let observe = crate::request_log::Observe {
model: state.model.name.clone(),
memory: state.model.memory.clone(),
};
Router::new()
.route("/health", get(health))
.route("/ready", get(ready))
.route("/status", get(status))
.route("/metrics", get(metrics))
.route("/api/health", get(crate::server_api::api_health))
.route("/props", get(crate::server_api::props))
.route("/slots", get(crate::server_api::slots))
.route("/v1/status", get(crate::server_api::v1_status))
.route("/v1/prefix_match", post(crate::server_api::v1_prefix_match))
.route("/v1/reconfigure", post(crate::server_api::v1_reconfigure))
.route("/mcp", get(crate::server_api::mcp_status))
.route(
"/settings",
get(crate::server_api::settings_get).post(crate::server_api::settings_post),
)
.route("/load", post(crate::server_api::load_post))
.route("/unload", post(crate::server_api::unload_post))
.route("/v1/load", post(crate::server_api::v1_load))
.route("/v1/unload", post(crate::server_api::v1_unload))
.route("/models", get(crate::models_api::list))
.route("/v1/models", get(crate::models_api::list))
.route("/v1/models/{id}", get(crate::models_api::retrieve))
.route(
"/v1/responses",
post(responses::create_route)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.services.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/responses/input_tokens",
post(responses::count_input_tokens).layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
)),
)
.route(
"/v1/chat/completions",
post(crate::chat::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn_with_state(
state.services.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route(
"/v1/messages/count_tokens",
post(crate::messages::count_tokens)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol)),
)
.route(
"/v1/messages",
post(crate::messages::create)
.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
.layer(middleware::from_fn(crate::messages::protocol))
.layer(middleware::from_fn_with_state(
state.services.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
)),
)
.route("/api/requests", get(crate::server_api::api_requests))
.route("/admin/lifecycle", get(lifecycle_status))
.route(
"/v1/responses/{id}",
get(responses::retrieve).delete(responses::delete),
)
.route(
"/v1/responses/{id}/input_items",
get(responses::input_items),
)
.route("/admin/drain", post(drain))
.route("/admin/resume", post(resume))
.fallback(crate::server_api::not_found)
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
state.http.api_key.clone(),
crate::auth::authorize,
))
// Outermost: a browser's credential-less preflight is answered before authentication.
.layer(middleware::from_fn_with_state(
state.http.cors.clone(),
crate::server_api::cors_layer,
))
.with_state(state)
}
+146
View File
@@ -0,0 +1,146 @@
//! The state every handler shares, grouped by responsibility (STRA-338 S7). A group is a small struct of
//! related handles; ports (`crate::ports`) are held as trait objects, never as the concrete adapter.
use std::{sync::Arc, time::SystemTime};
use tokio::sync::{RwLock, mpsc};
use crate::{
adapters::{ChannelEngine, SystemClock},
codec::TextCodec,
ports::{SharedClock, SharedEngine, SharedResponseStore, SharedToolHub, SharedVisionEncoder},
responses,
worker::{Control, GenerationCommand, WorkerStatus},
};
#[derive(Clone, Default)]
pub struct AppState {
/// Admission, drain and the in-flight count (also the `/v1/responses` admission middleware).
pub lifecycle: crate::lifecycle::Lifecycle,
/// The engine side: where generations go, how it is doing, and how to load/unload it.
pub engine: EngineLink,
/// Who may call the API: the key, the browser origins.
pub http: HttpPolicy,
/// The model as clients see it: its names, tokenizer, template and the engine's published views of it.
pub model: ModelView,
/// Stores and process-wide services: stored Responses, the request monitor, MCP, settings, the clock.
pub services: Services,
}
/// The engine side of the gateway.
#[derive(Clone)]
pub struct EngineLink {
/// The port generations are submitted to; `None` until a worker is configured.
pub client: Option<SharedEngine>,
/// Administrative channel to the worker supervisor (load/unload); `None` without a worker.
pub control: Option<mpsc::Sender<Control>>,
pub worker: Arc<RwLock<WorkerStatus>>,
/// With a worker pool, the status of every member (the first is `worker`); empty otherwise.
pub pool: Vec<Arc<RwLock<WorkerStatus>>>,
/// Longest a request may wait for the engine to claim it (`queue_timeout` in the config).
pub queue_timeout: Option<std::time::Duration>,
}
/// Who may call the API.
#[derive(Clone)]
pub struct HttpPolicy {
pub api_key: Option<Arc<crate::auth::ApiKey>>,
/// Browser pages of these origins may call `/v1/*`.
pub cors: Arc<leleka_serving_policy::cors::Cors>,
/// Origins that count as this server's own page for `/settings` and `/v1/load|unload`.
pub trusted_origins: Arc<Vec<String>>,
}
/// The model as clients see it.
#[derive(Clone)]
pub struct ModelView {
pub name: Option<String>,
/// Other names of the model (`aliases` in the config), answered like the model's own.
pub aliases: Arc<Vec<String>>,
pub tokenizer: Option<Arc<dyn TextCodec>>,
/// Source of the model's chat template, served by `/props`.
pub chat_template: Option<Arc<str>>,
/// The resident image encoder (`vision` in the config); `None`: this server cannot read images.
pub vision: Option<SharedVisionEncoder>,
/// The engine's prefix-cache summary for a pool router (`GET /v1/status`, `POST /v1/prefix_match`).
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`
/// (`docs/memory-safety.md`).
pub memory: Arc<crate::memory_view::MemoryView>,
}
/// Stores and process-wide services.
#[derive(Clone)]
pub struct Services {
/// Stored Responses (`store`, `previous_response_id`, `GET/DELETE /v1/responses/{id}`).
pub responses: SharedResponseStore,
/// The API request monitor (`api_monitor` in the config; off by default): `GET /api/requests`.
pub monitor: Arc<crate::request_monitor::RequestMonitor>,
/// The MCP servers configured for the operator (`GET /mcp`).
pub mcp: Option<SharedToolHub>,
pub settings: Arc<crate::settings::Settings>,
/// Wall and monotonic time: queue deadlines, uptime, response timestamps.
pub clock: SharedClock,
pub started_at: SystemTime,
}
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<GenerationCommand> {
let (client, receiver) = ChannelEngine::channel(capacity, self.services.clock.clone());
self.engine.client = Some(client);
receiver
}
}
impl Default for EngineLink {
fn default() -> Self {
Self {
client: None,
control: None,
worker: Arc::new(RwLock::new(WorkerStatus::default())),
pool: Vec::new(),
queue_timeout: None,
}
}
}
impl Default for HttpPolicy {
fn default() -> Self {
Self {
api_key: None,
cors: Arc::new(Default::default()),
trusted_origins: Arc::new(Vec::new()),
}
}
}
impl Default for ModelView {
fn default() -> Self {
Self {
name: None,
aliases: Arc::new(Vec::new()),
tokenizer: None,
chat_template: None,
vision: None,
prefix_cache: Arc::new(Default::default()),
memory: Arc::new(Default::default()),
}
}
}
impl Default for Services {
fn default() -> Self {
let clock = SystemClock::shared();
Self {
responses: responses::HistoryResponseStore::shared(
responses::ResponseHistory::default(),
),
monitor: Arc::new(Default::default()),
mcp: None,
settings: Arc::new(crate::settings::Settings::default()),
started_at: clock.system_time(),
clock,
}
}
}
+8 -4
View File
@@ -1,6 +1,7 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use crate::{adapters::ChannelEngine, worker::GenerationCommand};
#[tokio::test]
async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation() {
@@ -87,7 +88,7 @@ async fn drain_rejects_new_requests_before_json_parsing_and_resume_is_idempotent
false
);
drop(job);
state.worker.write().await.state = WorkerState::Restarting;
state.engine.worker.write().await.state = WorkerState::Restarting;
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
@@ -114,9 +115,12 @@ async fn drain_rejects_new_requests_before_json_parsing_and_resume_is_idempotent
#[tokio::test]
async fn metrics_expose_activity_without_changing_discovery() {
let (sender, mut receiver) = mpsc::channel(2);
let (sender, mut receiver) = tokio::sync::mpsc::channel(2);
let state = AppState {
generation: Some(sender.clone()),
engine: EngineLink {
client: Some(ChannelEngine::shared(sender.clone())),
..Default::default()
},
..Default::default()
};
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
@@ -137,7 +141,7 @@ async fn metrics_expose_activity_without_changing_discovery() {
})
.await
.unwrap();
state.worker.write().await.metrics.start();
state.engine.worker.write().await.metrics.start();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/metrics", listener.local_addr().unwrap());
let router = router(state.clone());
+1 -2
View File
@@ -1,6 +1,5 @@
//! Immutable, manifest-pinned assets acquired before native serving starts.
use std::{
error::Error,
fs::{self, File, OpenOptions},
io,
path::{Component, Path, PathBuf},
@@ -10,7 +9,7 @@ use serde::Deserialize;
use crate::model;
type Result<T> = std::result::Result<T, Box<dyn Error>>;
type Result<T> = std::result::Result<T, crate::BoxError>;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
+4 -1
View File
@@ -173,7 +173,10 @@ mod tests {
#[tokio::test]
async fn protected_routes_fail_before_body_parsing_and_health_stays_public() {
let state = crate::app::AppState {
api_key: Some(Arc::new(ApiKey::from_token(KEY).unwrap())),
http: crate::app::HttpPolicy {
api_key: Some(Arc::new(ApiKey::from_token(KEY).unwrap())),
..Default::default()
},
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+1 -83
View File
@@ -8,7 +8,6 @@ use axum::{
response::{IntoResponse, Response, Sse, sse::Event},
};
use futures_core::Stream;
use serde::Deserialize;
use serde_json::{Value, json};
use std::{
convert::Infallible,
@@ -18,91 +17,10 @@ use std::{
use tokio::sync::mpsc;
use crate::native_events::{MAX_EVENT, NativeEvents};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Request {
model: String,
messages: Vec<Message>,
#[serde(default)]
stream: bool,
stream_options: Option<StreamOptions>,
n: Option<u32>,
max_tokens: Option<u32>,
max_completion_tokens: Option<u32>,
temperature: Option<f64>,
top_p: Option<f64>,
#[serde(default)]
tools: Vec<Tool>,
tool_choice: Option<Value>,
parallel_tool_calls: Option<bool>,
response_format: Option<Value>,
reasoning_effort: Option<String>,
store: Option<bool>,
stop: Option<Value>,
logprobs: Option<bool>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StreamOptions {
include_usage: Option<bool>,
include_obfuscation: Option<bool>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Message {
role: String,
content: Option<Value>,
tool_calls: Option<Vec<Call>>,
tool_call_id: Option<String>,
refusal: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Call {
id: String,
#[serde(rename = "type")]
kind: String,
function: CallFunction,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CallFunction {
name: String,
arguments: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Tool {
#[serde(rename = "type")]
kind: String,
function: Function,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Function {
name: String,
description: Option<String>,
parameters: Option<Value>,
strict: Option<bool>,
}
type Invalid = (&'static str, &'static str);
/// A message's content: plain text, or (user messages only) the list of text and picture parts in the Responses
/// shape (`input_text` / `input_image`), whose order the template keeps.
enum Content {
Text(String),
Parts(Vec<Value>),
}
use leleka_gateway_domain::chat_completions::{Request, call, finish, identity, usage};
struct Events(mpsc::Receiver<Event>);
mod invalid;
#[allow(unused_imports)]
pub use invalid::*;
mod impl_request;
#[allow(unused_imports)]
pub use impl_request::*;
mod completion;
#[allow(unused_imports)]
pub use completion::*;
+31
View File
@@ -0,0 +1,31 @@
//! Command-line dispatch of `strata-next`: each group of commands owns its own match, in this order.
mod kar_inspect;
mod kar_overlay;
mod kar_verify;
mod model_ensure;
mod model_fetch;
mod model_inspect;
mod model_prepare;
mod model_text;
mod operations;
mod report;
mod usage;
use strata_control::BoxError;
pub async fn run(args: &[String]) -> Result<(), BoxError> {
if operations::run(args).await?
|| model_fetch::run(args).await?
|| model_inspect::run(args).await?
|| model_ensure::run(args).await?
|| model_prepare::run(args).await?
|| kar_inspect::run(args).await?
|| kar_verify::run(args).await?
|| kar_overlay::run(args).await?
|| model_text::run(args).await?
{
return Ok(());
}
Err(usage::USAGE.into())
}
+99
View File
@@ -0,0 +1,99 @@
//! `model` commands that read a KAR file: row checksums, inspection and memory plans.
use std::path::Path;
use strata_control::{BoxError, kar, kar_memory};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[model, action, path, tensor, level]
if model == "model" && action == "checksum-kar-preview" =>
{
let values = kar::decode_preview_tensor(Path::new(path), tensor, level.parse()?)?;
println!("tensor={tensor} elements={} level={level}", values.len());
println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values));
println!("first={} last={}", values[0], values[values.len() - 1]);
Ok(())
}
[model, action, path, tensor, level, row_flag, row_id]
if model == "model" && action == "checksum-kar-row" && row_flag == "--row" =>
{
let row_id: u32 = row_id.parse()?;
let values = kar::decode_tensor_row(Path::new(path), tensor, level.parse()?, row_id)?;
println!(
"tensor={tensor} row_id={row_id} elements={} level={level}",
values.len()
);
println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values));
println!("first={} last={}", values[0], values[values.len() - 1]);
Ok(())
}
[model, action, path] if model == "model" && action == "inspect-kar" => {
let summary = kar::inspect(Path::new(path))?;
println!("KAR-2: {path}");
println!("size: {} bytes", summary.archive_bytes);
println!(
"tensors: {}; elements: {}",
summary.tensor_count, summary.total_elements
);
println!("source elements: {}", summary.source_total_elements);
println!("accounted bpw: {}", summary.accounted_bpw);
println!("source SHA-256: {}", hex::encode(summary.source_digest));
println!("source bytes: {}", summary.source_bytes);
println!("bounded metadata checks passed; payload CRCs and padding not checked");
Ok(())
}
[model, action, path, level_flag, level, budget_flag, budget]
if model == "model"
&& action == "plan-kar-memory"
&& level_flag == "--level"
&& budget_flag == "--budget-mib" =>
{
let budget_mib: u64 = budget.parse()?;
let budget_bytes = budget_mib
.checked_mul(1 << 20)
.ok_or("GPU budget overflow")?;
let report = kar_memory::plan(Path::new(path), level.parse()?, budget_bytes)?;
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
}
[
model,
action,
base_flag,
base,
overlay_flag,
overlay,
base_level_flag,
base_level,
overlay_level_flag,
overlay_level,
budget_flag,
budget,
] if model == "model"
&& action == "plan-kar-overlay-memory"
&& base_flag == "--base"
&& overlay_flag == "--overlay"
&& base_level_flag == "--base-level"
&& overlay_level_flag == "--overlay-level"
&& budget_flag == "--budget-mib" =>
{
let budget_mib: u64 = budget.parse()?;
let budget_bytes = budget_mib
.checked_mul(1 << 20)
.ok_or("GPU budget overflow")?;
let report = kar_memory::plan_selected(
Path::new(base),
Path::new(overlay),
base_level.parse()?,
overlay_level.parse()?,
budget_bytes,
)?;
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+103
View File
@@ -0,0 +1,103 @@
//! `model` commands on KAR overlays: prepare, compare and resolve.
use std::path::Path;
use strata_control::{BoxError, kar_overlay, model};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[
model,
action,
manifest_spec,
source_flag,
source_dir,
base_flag,
base_archive,
candidates_flag,
candidates_path,
output_flag,
destination,
] if model == "model"
&& action == "prepare-kar-overlay"
&& source_flag == "--source-dir"
&& base_flag == "--base"
&& candidates_flag == "--candidates"
&& output_flag == "--output" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let result = kar_overlay::prepare(
&manifest,
Path::new(source_dir),
Path::new(base_archive),
Path::new(candidates_path),
Path::new(destination),
)?;
println!("EXPERIMENTAL KAR precision overlay: {destination}");
println!(
"records: {}; bytes: {}",
result.record_count, result.archive_bytes
);
println!("overlay SHA-256: {}", hex::encode(result.archive_sha256));
println!(
"maximum selected-record relative L2: {:.8}",
result.maximum_relative_l2
);
println!("provenance: {}", result.provenance_path.display());
println!("not eligible for serving without model-quality and GPU gates");
Ok(())
}
[
model,
action,
manifest_spec,
source_flag,
source_dir,
base_flag,
base_archive,
overlay_flag,
overlay_archive,
output_flag,
report_path,
] if model == "model"
&& action == "compare-kar-overlay"
&& source_flag == "--source-dir"
&& base_flag == "--base"
&& overlay_flag == "--overlay"
&& output_flag == "--output" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let comparison = kar_overlay::compare(
&manifest,
Path::new(source_dir),
Path::new(base_archive),
Path::new(overlay_archive),
)?;
kar_overlay::write_comparison(Path::new(report_path), &comparison)?;
println!("complete selected-tensor L2/L3 comparison: {report_path}");
println!("records: {}", comparison.records.len());
println!("not a full-model quality or GPU performance result");
Ok(())
}
[
model,
action,
base_flag,
base_archive,
overlay_flag,
overlay_archive,
] if model == "model"
&& action == "resolve-kar-overlay"
&& base_flag == "--base"
&& overlay_flag == "--overlay" =>
{
let resolution =
kar_overlay::resolve_verified(Path::new(base_archive), Path::new(overlay_archive))?;
println!("{}", serde_json::to_string_pretty(&resolution)?);
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+248
View File
@@ -0,0 +1,248 @@
//! `model` commands that verify KAR files against their sources and analyze sharded KARs.
use std::path::Path;
use strata_control::{BoxError, kar, kar_quality, model, prepare_preview};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[model, action, path] if model == "model" && action == "verify-kar" => {
let summary = kar::verify(Path::new(path))?;
println!(
"verified KAR-2 metadata and {} payload CRCs",
summary.tensor_count
);
println!("source SHA-256: {}", hex::encode(summary.source_digest));
println!("source files not checked; use --manifest SPEC --source-dir DIR");
Ok(())
}
[model, action, archive, source_flag, source]
if model == "model" && action == "verify-iq3-preview" && source_flag == "--source" =>
{
let summary = prepare_preview::verify_iq3(Path::new(source), Path::new(archive))?;
println!("verified IQ3 preview: {archive}");
println!("tensors: {}", summary.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(summary.source_digest)
);
println!("original GGUF, provenance, KAR source records, and payload CRCs match");
println!("not a model quality or GPU execution result");
Ok(())
}
[model, action, archive, source_flag, source]
if model == "model"
&& action == "verify-mixed-preview"
&& source_flag == "--source" =>
{
let summary = prepare_preview::verify_mixed(Path::new(source), Path::new(archive))?;
println!("verified mixed preview: {archive}");
println!("tensors: {}", summary.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(summary.source_digest)
);
println!("original GGUF, provenance, KAR source records, and payload CRCs match");
println!("not a model quality or GPU execution result");
Ok(())
}
[
model,
action,
archive,
manifest_flag,
manifest_spec,
source_flag,
source_dir,
] if model == "model"
&& action == "verify-sharded-preview"
&& manifest_flag == "--manifest"
&& source_flag == "--source-dir" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let summary = prepare_preview::verify_sharded(
&manifest,
Path::new(source_dir),
Path::new(archive),
)?;
println!("verified sharded preview: {archive}");
println!("tensors: {}", summary.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(summary.source_digest)
);
println!("manifest shards, provenance, KAR source records, and payload CRCs match");
println!("not a model quality or GPU execution result");
Ok(())
}
[
model,
action,
archive,
manifest_flag,
manifest_spec,
source_flag,
source_dir,
levels_flag,
levels,
] if model == "model"
&& action == "verify-sharded-streamed"
&& manifest_flag == "--manifest"
&& source_flag == "--source-dir"
&& levels_flag == "--levels" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let summary = prepare_preview::verify_sharded_streamed(
&manifest,
Path::new(source_dir),
Path::new(archive),
levels.parse()?,
)?;
println!("verified experimental streamed sharded KAR-2: {archive}");
println!("tensors: {}", summary.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(summary.source_digest)
);
println!("manifest shards, provenance, KAR source records, and payload CRCs match");
println!("not a model quality or GPU execution result");
Ok(())
}
[
model,
action,
archive,
manifest_flag,
manifest_spec,
source_flag,
source_dir,
levels_flag,
levels,
ple_flag,
ple_limit,
] if model == "model"
&& action == "verify-sharded-streamed"
&& manifest_flag == "--manifest"
&& source_flag == "--source-dir"
&& levels_flag == "--levels"
&& ple_flag == "--ple-part-elements" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let limit: u64 = ple_limit.parse()?;
let summary = prepare_preview::verify_sharded_streamed_ple(
&manifest,
Path::new(source_dir),
Path::new(archive),
levels.parse()?,
limit,
)?;
println!("verified experimental PLE-partitioned KAR-2: {archive}");
println!("tensors: {}", summary.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(summary.source_digest)
);
println!("PLE maximum part elements: {limit}");
println!("manifest shards, provenance, KAR source records, and payload CRCs match");
println!("not a model quality or GPU execution result");
Ok(())
}
[
model,
action,
archive,
manifest_flag,
manifest_spec,
source_flag,
source_dir,
levels_flag,
levels,
output_flag,
report_path,
] if model == "model"
&& action == "analyze-sharded-kar"
&& manifest_flag == "--manifest"
&& source_flag == "--source-dir"
&& levels_flag == "--levels"
&& output_flag == "--output" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let report = kar_quality::analyze(
&manifest,
Path::new(source_dir),
Path::new(archive),
levels.parse()?,
)?;
kar_quality::write_report(Path::new(report_path), &report)?;
println!("sampled KAR reconstruction report: {report_path}");
println!("records: {}", report.records.len());
println!("archive SHA-256: {}", report.archive_sha256);
println!("samples are not a full-tensor or model-quality gate");
Ok(())
}
[
model,
action,
archive,
manifest_flag,
manifest_spec,
source_flag,
source_dir,
levels_flag,
levels,
output_flag,
report_path,
assume_flag,
] if model == "model"
&& action == "analyze-sharded-kar"
&& manifest_flag == "--manifest"
&& source_flag == "--source-dir"
&& levels_flag == "--levels"
&& output_flag == "--output"
&& assume_flag == "--assume-verified" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let report = kar_quality::analyze_previously_verified(
&manifest,
Path::new(source_dir),
Path::new(archive),
levels.parse()?,
)?;
kar_quality::write_report(Path::new(report_path), &report)?;
println!("sampled KAR reconstruction report: {report_path}");
println!("records: {}", report.records.len());
println!(
"archive SHA-256 from previously verified provenance: {}",
report.archive_sha256
);
println!("full archive and source hashes were not recomputed in this run");
println!("samples are not a full-tensor or model-quality gate");
Ok(())
}
[
model,
action,
path,
manifest_flag,
manifest_spec,
source_flag,
source_dir,
] if model == "model"
&& action == "verify-kar"
&& manifest_flag == "--manifest"
&& source_flag == "--source-dir" =>
{
let summary = kar::verify(Path::new(path))?;
let manifest = model::Manifest::from_spec(manifest_spec).await?;
kar::verify_source_files(&summary, &manifest, Path::new(source_dir))?;
println!(
"verified KAR-2 metadata, {} payload CRCs, and source identity",
summary.tensor_count
);
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+172
View File
@@ -0,0 +1,172 @@
//! `model ensure-sharded-*`: build a KAR from a sharded manifest unless it is already there and valid.
use std::path::Path;
use strata_control::{BoxError, model, model_pipeline};
use super::report::print_top_tensor_distortions;
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[
model,
action,
manifest_spec,
source_flag,
source_dir,
output_flag,
destination,
levels_flag,
levels,
] if model == "model"
&& action == "ensure-sharded-preview"
&& source_flag == "--source-dir"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let outcome = model_pipeline::ensure_sharded_preview(
&manifest,
Path::new(source_dir),
Path::new(destination),
levels.parse()?,
)
.await?;
match outcome {
model_pipeline::PreviewOutcome::Created(result) => {
println!("created and verified experimental KAR-2: {destination}");
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
}
model_pipeline::PreviewOutcome::Reused(summary) => {
println!("reused verified experimental KAR-2: {destination}");
println!("tensors: {}", summary.tensor_count);
}
}
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[
model,
action,
manifest_spec,
source_flag,
source_dir,
output_flag,
destination,
levels_flag,
levels,
] if model == "model"
&& action == "ensure-sharded-streamed"
&& source_flag == "--source-dir"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let outcome = model_pipeline::ensure_sharded_streamed(
&manifest,
Path::new(source_dir),
Path::new(destination),
levels.parse()?,
)
.await?;
let source_bytes = manifest
.files
.iter()
.try_fold(0u64, |sum, file| sum.checked_add(file.size))
.ok_or("sharded source byte count overflow")?;
match outcome {
model_pipeline::PreviewOutcome::Created(result) => {
println!("created and verified experimental streamed KAR-2: {destination}");
println!("archive bytes: {}", result.archive.archive_bytes);
println!("source GGUF bytes: {source_bytes}");
println!(
"archive/source ratio: {:.6}",
result.archive.archive_bytes as f64 / source_bytes as f64
);
println!(
"accounted bits per weight: {:.6}",
result.archive.accounted_bpw
);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
print_top_tensor_distortions(&result.tensor_distortions);
}
model_pipeline::PreviewOutcome::Reused(summary) => {
println!("reused verified experimental streamed KAR-2: {destination}");
println!("archive bytes: {}", summary.archive_bytes);
println!("source GGUF bytes: {source_bytes}");
println!(
"archive/source ratio: {:.6}",
summary.archive_bytes as f64 / source_bytes as f64
);
println!("accounted bits per weight: {:.6}", summary.accounted_bpw);
println!("tensors: {}", summary.tensor_count);
}
}
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[
model,
action,
manifest_spec,
source_flag,
source_dir,
output_flag,
destination,
levels_flag,
levels,
ple_flag,
ple_limit,
] if model == "model"
&& action == "ensure-sharded-streamed"
&& source_flag == "--source-dir"
&& output_flag == "--output"
&& levels_flag == "--levels"
&& ple_flag == "--ple-part-elements" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let limit: u64 = ple_limit.parse()?;
let outcome = model_pipeline::ensure_sharded_streamed_ple(
&manifest,
Path::new(source_dir),
Path::new(destination),
levels.parse()?,
limit,
)
.await?;
match outcome {
model_pipeline::PreviewOutcome::Created(result) => {
println!(
"created and verified experimental PLE-partitioned KAR-2: {destination}"
);
println!("archive bytes: {}", result.archive.archive_bytes);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
print_top_tensor_distortions(&result.tensor_distortions);
}
model_pipeline::PreviewOutcome::Reused(summary) => {
println!("reused verified experimental PLE-partitioned KAR-2: {destination}");
println!("archive bytes: {}", summary.archive_bytes);
println!("tensors: {}", summary.tensor_count);
}
}
println!("PLE maximum part elements: {limit}");
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+103
View File
@@ -0,0 +1,103 @@
//! `model` commands that fetch, verify and convert model files: manifests, fixtures, native packs, tensor export.
use std::path::Path;
use strata_control::{BoxError, kar_fixture, model};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[
model,
action,
spec,
source_flag,
source,
output_flag,
output,
options @ ..,
] if model == "model"
&& action == "prepare-native-pack"
&& source_flag == "--source-dir"
&& output_flag == "--output" =>
{
let manifest = strata_control::model::Manifest::from_spec(spec).await?;
let mut pack = strata_control::native_pack::Options::default();
let mut options = options.iter();
while let Some(flag) = options.next() {
match flag.as_str() {
"--compat-bf16" => pack.compat_bf16 = true,
"--experts-bin" => pack.experts_bin = true,
"--base" => {
pack.base = Some(
options
.next()
.ok_or("--base needs a pack directory")?
.into(),
)
}
_ => return Err(format!("unknown prepare-native-pack option {flag}").into()),
}
}
println!(
"{}",
strata_control::native_pack::prepare_with(
&manifest,
Path::new(source),
Path::new(output),
&pack
)
.await?
);
Ok(())
}
[model, action, source, tensor, flag, output]
if model == "model" && action == "export-tensor-f32" && flag == "--output" =>
{
let report = strata_control::tensor_export::export(
Path::new(source),
tensor,
Path::new(output),
)?;
println!("{}", serde_json::to_string(&report)?);
Ok(())
}
[model, action, flag, output]
if model == "model" && action == "smoke-fixture" && flag == "--output" =>
{
let result = kar_fixture::write(Path::new(output))?;
println!("KAR-2 smoke fixture: {output}");
println!("tensor=smoke.expert elements=32 level=2");
println!("archive_sha256={}", hex::encode(result.archive_digest));
println!("output_fnv1a64={:x}", result.decoded_fnv1a64);
Ok(())
}
[model, action, flag, output]
if model == "model" && action == "ple-smoke-fixture" && flag == "--output" =>
{
let result = kar_fixture::write_ple(Path::new(output))?;
println!("KAR-2 PLE smoke fixture: {output}");
println!("archive_sha256={}", hex::encode(result.archive_digest));
for (row, checksum) in result.row_fnv1a64.iter().enumerate() {
println!("row={row} fnv1a64={checksum:016x}");
}
Ok(())
}
[model, action, manifest, flag, output]
if model == "model" && flag == "--output" && action == "fetch" =>
{
let manifest = model::Manifest::from_spec(manifest).await?;
model::fetch(&manifest, Path::new(output)).await?;
Ok(())
}
[model, action, manifest, flag, output]
if model == "model" && flag == "--output" && action == "verify" =>
{
let manifest = model::Manifest::from_spec(manifest).await?;
model::verify(&manifest, Path::new(output)).await?;
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+135
View File
@@ -0,0 +1,135 @@
//! `model` commands that read a GGUF file: metadata, tensor index and the derived identities.
use std::path::Path;
use strata_control::{BoxError, derived_iq3, derived_mixed, gguf, model};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[model, action, path] if model == "model" && action == "inspect-metadata" => {
// Every key/value as one JSON object; non-finite floats are the strings "nan", "inf", "-inf".
let entries = gguf::metadata_entries(Path::new(path))?;
println!("{}", strata_control::gguf_json::metadata_json(entries));
Ok(())
}
[model, action, path] if model == "model" && action == "inspect" => {
let summary = gguf::inspect(Path::new(path))?;
println!("GGUF v3: {path}");
println!("size: {} bytes", summary.file_size);
println!(
"tensors: {}; metadata: {}",
summary.tensors, summary.metadata
);
println!("data starts at byte {}", summary.data_start);
if let Some(architecture) = summary.architecture {
println!("architecture: {architecture}");
}
if let (Some(no), Some(count)) = (summary.split_no, summary.split_count) {
println!("split: {}/{}", no + 1, count);
}
println!("tensor types: {:?}", summary.types);
Ok(())
}
[model, action, path] if model == "model" && action == "index" => {
print_tensor_index(Path::new(path), false)
}
[model, action, path, hash_flag]
if model == "model" && action == "index" && hash_flag == "--hash" =>
{
print_tensor_index(Path::new(path), true)
}
[model, action, path] if model == "model" && action == "derive-iq3-identity" => {
let identity = derived_iq3::fingerprint(Path::new(path))?;
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"derivation": "strata-next/iq3_s-to-f32-le-v1",
"gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"iq3_sha256": hex::encode(tensor.iq3_sha256),
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
}))?
);
Ok(())
}
[model, action, path] if model == "model" && action == "derive-mixed-identity" => {
let identity = derived_mixed::fingerprint(Path::new(path))?;
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"derivation": "strata-next/gguf-mixed-to-f32-le-v1",
"gguf_sha256": hex::encode(identity.gguf_sha256),
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"source_kind": tensor.source_kind,
"source_sha256": hex::encode(tensor.source_sha256),
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
}))?
);
Ok(())
}
[model, action, manifest_spec, source_flag, source_dir]
if model == "model"
&& action == "derive-sharded-identity"
&& source_flag == "--source-dir" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let identity = derived_mixed::fingerprint_shards(&manifest, Path::new(source_dir))?;
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"derivation": "strata-next/gguf-shards-to-f32-le-v1",
"derived_f32_sha256": hex::encode(identity.derived_sha256),
"derived_f32_bytes": identity.derived_bytes,
"shards": identity.shards.iter().map(|shard| serde_json::json!({
"name": shard.name,
"gguf_sha256": hex::encode(shard.gguf_sha256),
"gguf_bytes": shard.gguf_bytes,
"tensor_count": shard.tensor_count,
})).collect::<Vec<_>>(),
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
"name": tensor.name,
"source_kind": tensor.source_kind,
"source_sha256": hex::encode(tensor.source_sha256),
"derived_offset": tensor.derived_offset,
"derived_bytes": tensor.derived_bytes,
"f32_sha256": hex::encode(tensor.f32_sha256),
})).collect::<Vec<_>>(),
}))?
);
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
fn print_tensor_index(path: &Path, hash: bool) -> Result<(), BoxError> {
let index = gguf::tensor_index(path)?;
for (number, tensor) in index.tensors.iter().enumerate() {
let mut row = serde_json::json!({
"name": tensor.name,
"dimensions": tensor.dimensions,
"type": tensor.kind,
"offset": index.summary.data_start + tensor.offset,
"bytes": tensor.bytes,
});
if hash {
row["sha256"] = hex::encode(gguf::tensor_sha256(path, &index, number)?).into();
}
println!("{row}");
}
Ok(())
}
+246
View File
@@ -0,0 +1,246 @@
//! `model prepare-*`: build a KAR preview from a GGUF or a sharded manifest.
use std::path::Path;
use strata_control::{BoxError, model, prepare_preview};
use super::report::print_top_tensor_distortions;
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[
model,
action,
source,
output_flag,
destination,
levels_flag,
levels,
] if model == "model"
&& action == "prepare-f32-preview"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let result = prepare_preview::prepare_f32(
Path::new(source),
Path::new(destination),
levels.parse()?,
)?;
println!("EXPERIMENTAL F32 preview KAR-2: {destination}");
println!("tensors: {}", result.archive.tensor_count);
println!(
"source SHA-256: {}",
hex::encode(result.archive.source_digest)
);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[
model,
action,
source,
output_flag,
destination,
levels_flag,
levels,
] if model == "model"
&& action == "prepare-iq3-preview"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let result = prepare_preview::prepare_iq3(
Path::new(source),
Path::new(destination),
levels.parse()?,
)?;
println!("EXPERIMENTAL IQ3_S-derived F32 KAR-2: {destination}");
println!("tensors: {}", result.archive.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(result.archive.source_digest)
);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!("provenance: {}", result.provenance_path.unwrap().display());
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[
model,
action,
source,
output_flag,
destination,
levels_flag,
levels,
] if model == "model"
&& action == "prepare-mixed-preview"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let result = prepare_preview::prepare_mixed(
Path::new(source),
Path::new(destination),
levels.parse()?,
)?;
println!("EXPERIMENTAL mixed GGUF-derived F32 KAR-2: {destination}");
println!("tensors: {}", result.archive.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(result.archive.source_digest)
);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!("provenance: {}", result.provenance_path.unwrap().display());
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[
model,
action,
manifest_spec,
source_flag,
source_dir,
output_flag,
destination,
levels_flag,
levels,
] if model == "model"
&& action == "prepare-sharded-preview"
&& source_flag == "--source-dir"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let result = prepare_preview::prepare_sharded(
&manifest,
Path::new(source_dir),
Path::new(destination),
levels.parse()?,
)?;
println!("EXPERIMENTAL sharded GGUF-derived F32 KAR-2: {destination}");
println!("tensors: {}", result.archive.tensor_count);
println!(
"derived F32 SHA-256: {}",
hex::encode(result.archive.source_digest)
);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!("provenance: {}", result.provenance_path.unwrap().display());
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[
model,
action,
manifest_spec,
source_flag,
source_dir,
output_flag,
destination,
levels_flag,
levels,
] if model == "model"
&& action == "prepare-sharded-streamed"
&& source_flag == "--source-dir"
&& output_flag == "--output"
&& levels_flag == "--levels" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let result = prepare_preview::prepare_sharded_streamed(
&manifest,
Path::new(source_dir),
Path::new(destination),
levels.parse()?,
)?;
let source_bytes = manifest
.files
.iter()
.try_fold(0u64, |sum, file| sum.checked_add(file.size))
.ok_or("sharded source byte count overflow")?;
println!("EXPERIMENTAL streamed sharded GGUF-derived F32 KAR-2: {destination}");
println!("tensors: {}", result.archive.tensor_count);
println!("archive bytes: {}", result.archive.archive_bytes);
println!("source GGUF bytes: {source_bytes}");
println!(
"archive/source ratio: {:.6}",
result.archive.archive_bytes as f64 / source_bytes as f64
);
println!(
"accounted bits per weight: {:.6}",
result.archive.accounted_bpw
);
println!(
"derived F32 SHA-256: {}",
hex::encode(result.archive.source_digest)
);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!("provenance: {}", result.provenance_path.unwrap().display());
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
print_top_tensor_distortions(&result.tensor_distortions);
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
[
model,
action,
manifest_spec,
source_flag,
source_dir,
output_flag,
destination,
levels_flag,
levels,
ple_flag,
ple_limit,
] if model == "model"
&& action == "prepare-sharded-streamed"
&& source_flag == "--source-dir"
&& output_flag == "--output"
&& levels_flag == "--levels"
&& ple_flag == "--ple-part-elements" =>
{
let manifest = model::Manifest::from_spec(manifest_spec).await?;
let limit: u64 = ple_limit.parse()?;
let result = prepare_preview::prepare_sharded_streamed_ple(
&manifest,
Path::new(source_dir),
Path::new(destination),
levels.parse()?,
limit,
)?;
println!("EXPERIMENTAL PLE-partitioned KAR-2: {destination}");
println!("tensors: {}", result.archive.tensor_count);
println!("archive bytes: {}", result.archive.archive_bytes);
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
println!("PLE maximum part elements: {limit}");
println!(
"maximum tensor relative L2: {:.8}",
result.maximum_relative_l2
);
print_top_tensor_distortions(&result.tensor_distortions);
println!("not eligible for serving without a full-model quality gate");
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+148
View File
@@ -0,0 +1,148 @@
//! `model` commands on the tokenizer and the chat template: extract, tokenize, detokenize, render.
use std::{io::Read, path::Path};
use strata_control::{BoxError, tokenizer, tokenizer_assets};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[model, action, path, flag, output]
if model == "model" && action == "extract-tokenizer" && flag == "--output" =>
{
let destination = tokenizer_assets::extract(Path::new(path), Path::new(output))?;
println!("extracted {}", destination.display());
Ok(())
}
[model, action, path, input]
if model == "model" && action == "tokenize" && input != "--stdin" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(input, false)?)?
);
Ok(())
}
[model, action, path, input, flag]
if model == "model"
&& action == "tokenize"
&& input != "--stdin"
&& flag == "--special" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(input, true)?)?
);
Ok(())
}
[model, action, path, flag]
if model == "model" && action == "tokenize" && flag == "--stdin" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(&input, false)?)?
);
Ok(())
}
[model, action, path, stdin_flag, special_flag]
if model == "model"
&& action == "tokenize"
&& stdin_flag == "--stdin"
&& special_flag == "--special" =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;
println!(
"{}",
serde_json::to_string(&tokenizer.encode(&input, true)?)?
);
Ok(())
}
[model, action, path, ids] if model == "model" && action == "detokenize" => {
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
let ids = if ids.is_empty() {
Vec::new()
} else {
ids.split(',')
.map(str::parse::<u32>)
.collect::<Result<Vec<_>, _>>()?
};
println!("{}", serde_json::to_string(&tokenizer.decode(&ids)?)?);
Ok(())
}
// Batch forms for the differential harness (scripts/offline/diff_tokenizer.py): one JSON value per line.
[model, action] if model == "model" && action == "pre-tokenize-batch" => {
for line in std::io::stdin().lines() {
let text: String = serde_json::from_str(&line?)?;
let pieces = tokenizer::pre_tokenize(&text);
println!("{}", serde_json::to_string(&pieces.ok())?);
}
Ok(())
}
[model, action, path, rest @ ..]
if model == "model"
&& action == "tokenize-batch"
&& rest.iter().all(|flag| flag == "--special") =>
{
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
for line in std::io::stdin().lines() {
let text: String = serde_json::from_str(&line?)?;
let ids = tokenizer.encode(&text, !rest.is_empty()).ok();
println!("{}", serde_json::to_string(&ids)?);
}
Ok(())
}
// JSON lines {"messages": [...], "tools": [...]|null, "add_generation_prompt": true, "kwargs": {...}} ->
// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template, for scripts/offline/diff_chat_template.py.
[model, action] if model == "model" && action == "render-chat" => {
use strata_control::prompt::{ChatInput, Json, pinned};
for line in std::io::stdin().lines() {
let request: Json = serde_json::from_str(&line?)?;
let array = |key: &str| match request.get(key) {
Some(Json::Array(items)) => Some(items.as_slice()),
_ => None,
};
let kwargs = match request.get("kwargs") {
Some(Json::Object(fields)) => fields
.iter()
.map(|(k, v)| (k.as_str(), v.clone()))
.collect(),
_ => Vec::new(),
};
let rendered = pinned().render(&ChatInput {
messages: array("messages").unwrap_or(&[]),
tools: array("tools"),
add_generation_prompt: !matches!(
request.get("add_generation_prompt"),
Some(Json::Bool(false))
),
kwargs,
});
println!(
"{}",
match rendered {
Ok(text) => serde_json::json!({"ok": text}),
Err(message) => serde_json::json!({"error": message}),
}
);
}
Ok(())
}
[model, action, path] if model == "model" && action == "detokenize-batch" => {
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
for line in std::io::stdin().lines() {
let ids: Vec<u32> = serde_json::from_str(&line?)?;
println!("{}", serde_json::to_string(&tokenizer.decode(&ids).ok())?);
}
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+124
View File
@@ -0,0 +1,124 @@
//! Service operation commands: serve, provision, check-config, wait-ready, service-*, doctor, engine info, api-key,
//! the offline `tools` and the version/licence lines.
use std::{env, path::Path};
use strata_control::{BoxError, config::Config, doctor};
/// Run the command in `args` if this group owns it; `Ok(false)` when it does not.
pub async fn run(args: &[String]) -> Result<bool, BoxError> {
let handled: Result<(), BoxError> = match args {
[command, sub, rest @ ..] if command == "tools" && sub == "mtp-fetch" => {
let code = strata_control::mtp_fetch::cli(rest).await?;
if code != 0 {
std::process::exit(code);
}
Ok(())
}
[command, rest @ ..] if command == "tools" => {
print!("{}", leleka_offline_tools::cli::run(rest)?);
Ok(())
}
[command, rest @ ..] if command == "api-key" => {
println!("{}", strata_control::key_init::run(rest)?);
Ok(())
}
[command, flag, path, defer]
if command == "provision" && flag == "--config" && defer == "--defer-memory-check" =>
{
let mut config = Config::load_with_path(Some(Path::new(path)))?;
config.prepare_for_switch().await?;
println!(
"{}",
serde_json::json!({"assets_verified": config.assets.len(), "native_model_prepared":config.native_model.is_some(), "mtp_pack_structurally_validated":config.mtp_pack.is_some(), "worker_started": false, "memory_admission": "deferred_until_serve"})
);
Ok(())
}
[command, flag, path] if command == "provision" && flag == "--config" => {
let mut config = Config::load_with_path(Some(Path::new(path)))?;
config.provision().await?;
println!(
"{}",
serde_json::json!({"assets_verified": config.assets.len(), "native_model_prepared":config.native_model.is_some(), "mtp_pack_structurally_validated":config.mtp_pack.is_some(), "worker_started": false})
);
Ok(())
}
[command] if command == "check-config" => {
println!("{}", strata_control::preflight::check(None)?);
Ok(())
}
[command, flag, config] if command == "check-config" && flag == "--config" => {
println!(
"{}",
strata_control::preflight::check(Some(Path::new(config)))?
);
Ok(())
}
[command] if command == "engine-info" => {
println!("{}", strata_control::embedded_engine::info());
Ok(())
}
[command] if command == "engine-help" => strata_control::embedded_engine::help(),
[command] if command == "--engine-license" => {
print!("{}", include_str!("../../../engine/strata/LICENSE"));
Ok(())
}
[] => crate::serve::serve(None).await,
[command] if command == "serve" => crate::serve::serve(None).await,
[command, flag, config] if command == "serve" && flag == "--config" => {
crate::serve::serve(Some(Path::new(config))).await
}
[command, rest @ ..] if command == "wait-ready" => {
println!("{}", strata_control::wait_ready::run(rest).await?);
Ok(())
}
[command, rest @ ..] if command == "service-switch" => {
println!("{}", strata_control::service_switch::run(rest).await?);
Ok(())
}
[command, rest @ ..] if command == "service-control" => {
println!("{}", strata_control::service_install::control(rest).await?);
Ok(())
}
[command, rest @ ..] if command == "service-install" => {
println!("{}", strata_control::service_install::run(rest).await?);
Ok(())
}
[command, rest @ ..] if command == "service-unit" => {
let (config, working_dir, env_file) = match rest {
[config_flag, config, work_flag, working_dir]
if config_flag == "--config" && work_flag == "--working-dir" =>
(config, working_dir, None),
[config_flag, config, work_flag, working_dir, env_flag, env_file]
if config_flag == "--config" && work_flag == "--working-dir" && env_flag == "--env-file" =>
(config, working_dir, Some(Path::new(env_file))),
_ => return Err("usage: strata-next service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]".into()),
};
print!(
"{}",
strata_control::service_unit::render(
&env::current_exe()?,
Path::new(config),
Path::new(working_dir),
env_file,
)?
);
Ok(())
}
[doctor] if doctor == "doctor" => {
doctor::report().await?;
Ok(())
}
[version] if version == "--version" || version == "-V" => {
println!("strata-next {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
[license] if license == "--ggml-license" => {
println!("ggml IQ3_S grid table — MIT License\n");
print!("{}", include_str!("../../third_party/ggml/LICENSE"));
Ok(())
}
_ => return Ok(false),
};
handled.map(|()| true)
}
+18
View File
@@ -0,0 +1,18 @@
//! Output shared by the KAR preparation commands.
use strata_control::prepare_preview;
pub(super) fn print_top_tensor_distortions(distortions: &[prepare_preview::TensorDistortion]) {
let mut ranked = distortions.iter().collect::<Vec<_>>();
ranked.sort_by(|a, b| b.relative_l2.total_cmp(&a.relative_l2));
println!(
"highest relative L2 by KAR record (top 20 of {}):",
ranked.len()
);
for tensor in ranked.into_iter().take(20) {
println!(
" {:.8} kind={} bytes={} {}",
tensor.relative_l2, tensor.source_kind, tensor.section_bytes, tensor.name
);
}
}
+3
View File
@@ -0,0 +1,3 @@
//! The text printed for an unknown command line.
pub const USAGE: &str = "usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model pre-tokenize-batch|model tokenize-batch TOKENIZER_DIR [--special]|model detokenize-batch TOKENIZER_DIR|model render-chat|model detokenize TOKENIZER_DIR IDS|tools embd-bf16-pack --model DIR --out FILE.gguf|tools ple-fp8-pack --model DIR --out FILE.gguf|tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic] [--out IDS.bin] [--stats]|tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]|tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]]";
+4 -4
View File
@@ -162,12 +162,12 @@ struct ControlVectorFile {
#[cfg(test)]
mod tests;
mod impl_controlvector;
mod control_vector;
#[allow(unused_imports)]
pub use impl_controlvector::*;
mod impl_config;
pub use control_vector::*;
mod methods;
#[allow(unused_imports)]
pub use impl_config::*;
pub use methods::*;
mod optional_env;
#[allow(unused_imports)]
pub use optional_env::*;
-8
View File
@@ -1,8 +0,0 @@
//! Moved out of the parent module by STRA-338: impl Config.
#[allow(unused_imports)]
use super::*;
mod impl_config_2;
mod impl_config_2_2;
mod impl_config_3;
+9
View File
@@ -0,0 +1,9 @@
//! The methods of `Config`: loading the file and environment, provisioning assets, host checks.
#[allow(unused_imports)]
use super::*;
mod load;
mod load_sections;
mod load_with_path;
mod provision;
@@ -0,0 +1,243 @@
//! The sections of `Config::load_with_path` that stand alone: limits, the engine worker pool, the MCP servers.
//! Each reads the parsed file and the environment, checks its own ranges, and fails with the same messages and in the
//! same order as when it was one function.
#[allow(unused_imports)]
use super::*;
pub(super) struct Limits {
pub(super) bind: SocketAddr,
pub(super) max_in_flight_requests: usize,
pub(super) prompt_date: crate::responses::PromptDate,
pub(super) queue_timeout_s: Option<u64>,
pub(super) shutdown_grace_s: u64,
}
pub(super) struct EngineSection {
pub(super) worker: Option<WorkerConfig>,
pub(super) extra_workers: Vec<WorkerConfig>,
pub(super) idle_unload_s: Option<f64>,
}
pub(super) type Mcp = (
std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
crate::mcp::Settings,
);
impl Config {
pub(super) fn read_limits(file: &FileConfig) -> Result<Limits, crate::BoxError> {
let bind: SocketAddr = optional_env("STRATA_BIND")?
.or(file.bind.clone())
.unwrap_or_else(|| "127.0.0.1:8081".to_owned())
.parse()?;
let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.map(|value| value.parse::<usize>())
.transpose()?
.or(file.max_in_flight_requests)
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
let prompt_date = optional_env("STRATA_PROMPT_DATE")?
.or(file.prompt_date.clone())
.map(|text| crate::responses::PromptDate::parse(&text))
.transpose()?
.unwrap_or(crate::responses::PromptDate::Utc);
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
}
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.shutdown_grace_s)
.unwrap_or(0);
if shutdown_grace_s > 20 {
return Err("shutdown_grace_s must be between 0 and 20".into());
}
Ok(Limits {
bind,
max_in_flight_requests,
prompt_date,
queue_timeout_s,
shutdown_grace_s,
})
}
pub(super) fn read_engine(file: &FileConfig) -> Result<EngineSection, crate::BoxError> {
let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
});
let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")?
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?;
let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.startup_timeout_s)
})
.unwrap_or(600);
if !(1..=3600).contains(&startup_timeout_s) {
return Err("startup_timeout_s must be between 1 and 3600".into());
}
let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")?
.map(|value| value.parse::<u32>())
.transpose()?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts))
.unwrap_or(3);
if max_restarts > 3 {
return Err("max_restarts must be between 0 and 3".into());
}
let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("generation_timeout_s must be between 1 and 86400".into());
}
let engine_file = file.engine.as_ref();
let mut args = args;
if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) {
if args
.iter()
.any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-"))
{
return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into());
}
args.extend(vector.engine_args()?);
}
let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s);
if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("stall_timeout_s must be between 1 and 86400".into());
}
let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s);
if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) {
return Err("idle_unload_s must be a non-negative number".into());
}
let worker = match executable {
Some(executable) if !executable.is_empty() => Some(WorkerConfig {
executable,
cuda_memory: None,
args,
startup_timeout: Duration::from_secs(startup_timeout_s),
generation_timeout: generation_timeout_s.map(Duration::from_secs),
max_restarts,
lazy: engine_file.is_some_and(|engine| engine.lazy_load),
stall_timeout: stall_timeout_s.map(Duration::from_secs),
before_load: engine_file.and_then(|engine| engine.before_load.clone()),
min_free_vram_mib: engine_file
.and_then(|engine| engine.min_free_vram_mib)
.unwrap_or(0),
vision: None,
}),
Some(_) => return Err("engine executable cannot be empty".into()),
None if !args.is_empty() => return Err("engine args require an executable".into()),
None => None,
};
let extra = file
.engine
.as_ref()
.map(|engine| engine.extra_workers.as_slice())
.unwrap_or_default();
if !extra.is_empty() {
if file.runtime.is_some() {
return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into());
}
if engine_file.is_some_and(|engine| {
engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0)
}) {
return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into());
}
if file.vision.is_some() {
return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into());
}
}
if extra.len() > 7 {
return Err("at most 7 extra_workers".into());
}
let mut extra_workers = Vec::with_capacity(extra.len());
for entry in extra {
let Some(main) = worker.as_ref() else {
return Err("extra_workers require an engine executable".into());
};
if entry.executable.is_empty() {
return Err("an extra worker executable cannot be empty".into());
}
extra_workers.push(WorkerConfig {
executable: OsString::from(&entry.executable),
cuda_memory: None,
args: entry.args.clone(),
startup_timeout: main.startup_timeout,
generation_timeout: main.generation_timeout,
max_restarts: main.max_restarts,
lazy: false,
stall_timeout: main.stall_timeout,
before_load: None,
min_free_vram_mib: 0,
vision: None,
});
}
Ok(EngineSection {
worker,
extra_workers,
idle_unload_s,
})
}
/// The four MCP entries of the file: `mcp_servers`, `mcpServers`, `mcp_config_file` and the `mcp` settings block.
pub(super) fn read_mcp(
servers: Option<&serde_json::Value>,
desktop: Option<&serde_json::Value>,
config_file: Option<&Path>,
settings: Option<&serde_json::Value>,
) -> Result<Mcp, crate::BoxError> {
let mut mcp_servers = std::collections::BTreeMap::new();
let null = serde_json::Value::Null;
mcp_servers.extend(crate::mcp::servers_from(
servers.unwrap_or(&null),
"config mcp_servers",
)?);
mcp_servers.extend(crate::mcp::servers_from(
desktop.unwrap_or(&null),
"config mcpServers",
)?);
if let Some(path) = config_file {
// Claude Desktop's format; a name in both takes this file's entry.
let location = format!("mcp_config_file {}", path.display());
let text = std::fs::read_to_string(path)
.map_err(|error| format!("[strata] {location}: {error}"))?;
let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map_err(|error| format!("[strata] {location}: {error}"))?;
let block = data
.get("mcpServers")
.or_else(|| data.get("mcp_servers"))
.ok_or_else(|| {
format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}")
})?;
mcp_servers.extend(crate::mcp::servers_from(block, &location)?);
}
let mcp_settings = crate::mcp::settings_from(settings.unwrap_or(&null))?;
Ok((mcp_servers, mcp_settings))
}
}
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: impl Config (2).
//! `Config::load_with_path`: the file, the environment, and the cross-checks between the sections.
use super::load_sections::{EngineSection, Limits};
#[allow(unused_imports)]
use super::*;
@@ -19,166 +20,18 @@ impl Config {
if let Some(native) = &file.native_model {
native.validate(&file.assets)?;
}
let bind: SocketAddr = optional_env("STRATA_BIND")?
.or(file.bind)
.unwrap_or_else(|| "127.0.0.1:8081".to_owned())
.parse()?;
let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")?
.map(|value| value.parse::<usize>())
.transpose()?
.or(file.max_in_flight_requests)
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
let prompt_date = optional_env("STRATA_PROMPT_DATE")?
.or(file.prompt_date)
.map(|text| crate::responses::PromptDate::parse(&text))
.transpose()?
.unwrap_or(crate::responses::PromptDate::Utc);
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.queue_timeout_s);
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
}
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or(file.shutdown_grace_s)
.unwrap_or(0);
if shutdown_grace_s > 20 {
return Err("shutdown_grace_s must be between 0 and 20".into());
}
let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| {
file.engine
.as_ref()
.map(|engine| OsString::from(&engine.executable))
});
let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")?
.map(|value| serde_json::from_str::<Vec<String>>(&value))
.transpose()?;
let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?;
let configured_args = file.engine.as_ref().map(|engine| engine.args.clone());
let args = args_override.or(configured_args).unwrap_or_default();
let startup_timeout_s = timeout_override
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.startup_timeout_s)
})
.unwrap_or(600);
if !(1..=3600).contains(&startup_timeout_s) {
return Err("startup_timeout_s must be between 1 and 3600".into());
}
let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")?
.map(|value| value.parse::<u32>())
.transpose()?
.or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts))
.unwrap_or(3);
if max_restarts > 3 {
return Err("max_restarts must be between 0 and 3".into());
}
let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("generation_timeout_s must be between 1 and 86400".into());
}
let engine_file = file.engine.as_ref();
let mut args = args;
if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) {
if args
.iter()
.any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-"))
{
return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into());
}
args.extend(vector.engine_args()?);
}
let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s);
if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("stall_timeout_s must be between 1 and 86400".into());
}
let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s);
if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) {
return Err("idle_unload_s must be a non-negative number".into());
}
let worker = match executable {
Some(executable) if !executable.is_empty() => Some(WorkerConfig {
executable,
cuda_memory: None,
args,
startup_timeout: Duration::from_secs(startup_timeout_s),
generation_timeout: generation_timeout_s.map(Duration::from_secs),
max_restarts,
lazy: engine_file.is_some_and(|engine| engine.lazy_load),
stall_timeout: stall_timeout_s.map(Duration::from_secs),
before_load: engine_file.and_then(|engine| engine.before_load.clone()),
min_free_vram_mib: engine_file
.and_then(|engine| engine.min_free_vram_mib)
.unwrap_or(0),
vision: None,
}),
Some(_) => return Err("engine executable cannot be empty".into()),
None if !args.is_empty() => return Err("engine args require an executable".into()),
None => None,
};
let extra = file
.engine
.as_ref()
.map(|engine| engine.extra_workers.as_slice())
.unwrap_or_default();
if !extra.is_empty() {
if file.runtime.is_some() {
return Err("extra_workers and runtime are mutually exclusive: the pool feeds stdio engine children, a runtime block serves in front of one leleka-inference".into());
}
if engine_file.is_some_and(|engine| {
engine.lazy_load || engine.idle_unload_s.is_some_and(|seconds| seconds > 0.0)
}) {
return Err("extra_workers cannot be combined with lazy_load or idle_unload_s: the pool dispatcher does not load or unload workers on demand".into());
}
if file.vision.is_some() {
return Err("extra_workers cannot be combined with vision: images are read by the single supervised worker".into());
}
}
if extra.len() > 7 {
return Err("at most 7 extra_workers".into());
}
let mut extra_workers = Vec::with_capacity(extra.len());
for entry in extra {
let Some(main) = worker.as_ref() else {
return Err("extra_workers require an engine executable".into());
};
if entry.executable.is_empty() {
return Err("an extra worker executable cannot be empty".into());
}
extra_workers.push(WorkerConfig {
executable: OsString::from(&entry.executable),
cuda_memory: None,
args: entry.args.clone(),
startup_timeout: main.startup_timeout,
generation_timeout: main.generation_timeout,
max_restarts: main.max_restarts,
lazy: false,
stall_timeout: main.stall_timeout,
before_load: None,
min_free_vram_mib: 0,
vision: None,
});
}
let Limits {
bind,
max_in_flight_requests,
prompt_date,
queue_timeout_s,
shutdown_grace_s,
} = Self::read_limits(&file)?;
let EngineSection {
worker,
extra_workers,
idle_unload_s,
} = Self::read_engine(&file)?;
let mut tokenizer_dir = env::var_os("STRATA_TOKENIZER_DIR")
.map(PathBuf::from)
.or_else(|| {
@@ -349,32 +202,12 @@ impl Config {
.as_deref()
.map(crate::settings::default_shared_path)
});
let mut mcp_servers = std::collections::BTreeMap::new();
let null = serde_json::Value::Null;
mcp_servers.extend(crate::mcp::servers_from(
file.mcp_servers.as_ref().unwrap_or(&null),
"config mcp_servers",
)?);
mcp_servers.extend(crate::mcp::servers_from(
file.mcp_servers_desktop.as_ref().unwrap_or(&null),
"config mcpServers",
)?);
if let Some(path) = &file.mcp_config_file {
// Claude Desktop's format; a name in both takes this file's entry.
let location = format!("mcp_config_file {}", path.display());
let text = std::fs::read_to_string(path)
.map_err(|error| format!("[strata] {location}: {error}"))?;
let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map_err(|error| format!("[strata] {location}: {error}"))?;
let block = data
.get("mcpServers")
.or_else(|| data.get("mcp_servers"))
.ok_or_else(|| {
format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}")
})?;
mcp_servers.extend(crate::mcp::servers_from(block, &location)?);
}
let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?;
let (mcp_servers, mcp_settings) = Self::read_mcp(
file.mcp_servers.as_ref(),
file.mcp_servers_desktop.as_ref(),
file.mcp_config_file.as_deref(),
file.mcp.as_ref(),
)?;
if let Some(vision) = &file.vision {
vision.validate()?;
if worker.is_none() {
+4 -4
View File
@@ -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<dyn Error>> {
pub async fn report() -> Result<(), crate::BoxError> {
println!(
"platform: {} {}",
std::env::consts::OS,
@@ -29,7 +29,7 @@ pub async fn report() -> Result<(), Box<dyn Error>> {
Ok(())
}
pub async fn check(_requirement: GpuRequirement) -> Result<String, Box<dyn Error>> {
pub async fn check(_requirement: GpuRequirement) -> Result<String, crate::BoxError> {
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<String, Box<dyn Error
Ok(format!("{}.{}.{}", version.0, version.1, version.2))
}
async fn probe() -> Result<DriverVersion, Box<dyn Error>> {
async fn probe() -> Result<DriverVersion, crate::BoxError> {
let mut child = Command::new("nvidia-smi")
.args(["--query-gpu=driver_version", "--format=csv,noheader"])
.stdin(Stdio::null())
+5 -5
View File
@@ -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<Option<EmbeddedEngine>, Box<dyn Error>> {
pub fn resolve(executable: &OsStr) -> Result<Option<EmbeddedEngine>, crate::BoxError> {
if executable != OsStr::new("@embedded") {
return Ok(None);
}
@@ -39,7 +39,7 @@ pub fn resolve(executable: &OsStr) -> Result<Option<EmbeddedEngine>, Box<dyn Err
}
/// Explicit loader/help probe; this is not an inference or readiness check.
pub fn help() -> Result<(), Box<dyn Error>> {
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<dyn Error>> {
}
#[cfg(not(target_os = "linux"))]
fn materialize(_: &[u8]) -> Result<EmbeddedEngine, Box<dyn Error>> {
fn materialize(_: &[u8]) -> Result<EmbeddedEngine, crate::BoxError> {
Err("embedded worker execution requires Linux".into())
}
#[cfg(target_os = "linux")]
fn materialize(bytes: &[u8]) -> Result<EmbeddedEngine, Box<dyn Error>> {
fn materialize(bytes: &[u8]) -> Result<EmbeddedEngine, crate::BoxError> {
use std::{
io::Write,
os::fd::{AsRawFd, FromRawFd},
+2 -2
View File
@@ -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<dyn Error>> {
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)?;
+7 -5
View File
@@ -22,11 +22,16 @@ macro_rules! wlog {
}};
}
/// The boxed error the command-line and offline-tool functions return.
pub type BoxError = Box<dyn std::error::Error>;
pub use leleka_gateway_domain::{codec, json_order, reasoning_budget, sampling};
pub mod adapters;
pub mod app;
pub mod asset_bundle;
pub mod auth;
pub mod backend_worker;
pub mod codec;
pub mod config;
pub mod derived_iq3;
pub mod derived_mixed;
@@ -44,7 +49,6 @@ mod history_store;
mod immutable_directory;
pub use leleka_quant_core::iq3_s;
pub mod hardware_view;
pub mod json_order;
pub mod kar;
pub mod kar_codec;
pub mod kar_fixture;
@@ -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;
@@ -99,8 +104,6 @@ pub mod service_switch;
pub mod queue;
pub mod request_log;
pub mod sampling;
pub mod server_api;
pub mod stage_trace;
@@ -108,5 +111,4 @@ pub mod stage_trace;
pub mod settings;
pub mod mcp;
pub mod reasoning_budget;
pub mod vision;
+5 -1153
View File
File diff suppressed because it is too large Load Diff
+14 -14
View File
@@ -142,30 +142,30 @@ pub struct Hub {
#[cfg(test)]
mod tests;
mod impl_default_for_settings;
mod settings_default;
#[allow(unused_imports)]
pub use impl_default_for_settings::*;
mod impl_stdiotransport;
pub use settings_default::*;
mod stdio_transport;
#[allow(unused_imports)]
pub use impl_stdiotransport::*;
pub use stdio_transport::*;
mod dispatch;
#[allow(unused_imports)]
pub use dispatch::*;
mod impl_http;
mod http_transport;
#[allow(unused_imports)]
pub use impl_http::*;
mod impl_transport;
pub use http_transport::*;
mod transport;
#[allow(unused_imports)]
pub use impl_transport::*;
mod impl_server;
pub use transport::*;
mod server;
#[allow(unused_imports)]
pub use impl_server::*;
pub use server::*;
mod result_text;
#[allow(unused_imports)]
pub use result_text::*;
mod impl_hub;
mod hub;
#[allow(unused_imports)]
pub use impl_hub::*;
mod check_server;
pub use hub::*;
mod parse_config;
#[allow(unused_imports)]
pub use check_server::*;
pub use parse_config::*;
@@ -1,9 +1,9 @@
//! Moved out of the parent module by STRA-338: fn check_server, fn servers_from, fn settings_from.
//! Moved out of the parent module by STRA-338: fn parse_config, fn servers_from, fn settings_from.
#[allow(unused_imports)]
use super::*;
pub(super) fn check_server(
pub(super) fn parse_config(
name: &str,
config: &Value,
location: &str,
@@ -73,7 +73,7 @@ pub fn servers_from(
if config.get("disabled") == Some(&json!(true)) {
continue;
}
out.insert(name.clone(), check_server(name, config, location)?);
out.insert(name.clone(), parse_config(name, config, location)?);
}
}
_ => {
+1 -1
View File
@@ -21,7 +21,7 @@ use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
};
type Result<T> = std::result::Result<T, Box<dyn Error>>;
type Result<T> = std::result::Result<T, crate::BoxError>;
const FETCH_ATTEMPTS: usize = 4;
#[derive(Deserialize)]
+5 -6
View File
@@ -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<PreviewOutcome, Box<dyn Error>> {
) -> Result<PreviewOutcome, crate::BoxError> {
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<PreviewOutcome, Box<dyn Error>> {
) -> Result<PreviewOutcome, crate::BoxError> {
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<PreviewOutcome, Box<dyn Error>> {
) -> Result<PreviewOutcome, crate::BoxError> {
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<u64>,
) -> Result<PreviewOutcome, Box<dyn Error>> {
) -> Result<PreviewOutcome, crate::BoxError> {
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<dyn Error>> {
) -> 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 => {}
+18 -10
View File
@@ -24,22 +24,22 @@ fn record(id: &str, images: bool) -> Value {
/// The model and each configured alias (`alias_of` names the model), like the Original; an engine
/// that is unloaded on purpose says so (`status`) and still lists: it loads on use.
async fn records(state: &AppState) -> Vec<Value> {
let unloaded = state.worker.read().await.state == crate::worker::WorkerState::Unloaded;
let unloaded = state.engine.worker.read().await.state == crate::worker::WorkerState::Unloaded;
let mark = |mut value: Value| {
if unloaded {
value["status"] = json!({"value": "unloaded"});
}
value
};
let Some(model) = state.model.as_deref() else {
let Some(model) = state.model.name.as_deref() else {
return Vec::new();
};
let images = state.vision.is_some();
let images = state.model.vision.is_some();
let mut out = vec![mark(record(model, images))];
if !state.aliases.is_empty() {
out[0]["aliases"] = json!(*state.aliases);
if !state.model.aliases.is_empty() {
out[0]["aliases"] = json!(*state.model.aliases);
}
for alias in state.aliases.iter() {
for alias in state.model.aliases.iter() {
let mut value = mark(record(alias, images));
value["alias_of"] = json!(model);
out.push(value);
@@ -96,17 +96,25 @@ pub async fn retrieve(
#[cfg(test)]
mod tests {
use super::*;
use crate::adapters::ChannelEngine;
use crate::app::{EngineLink, ModelView};
#[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: EngineLink {
client: Some(ChannelEngine::shared(sender)),
..Default::default()
},
model: ModelView {
name: Some("org/model : v1".into()),
..Default::default()
},
..Default::default()
};
state.lifecycle.set_draining(true);
state.worker.write().await.state = crate::worker::WorkerState::Restarting;
state.engine.worker.write().await.state = crate::worker::WorkerState::Restarting;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let router = crate::app::router(state.clone());
@@ -139,7 +147,7 @@ mod tests {
assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0);
assert_eq!(state.lifecycle.snapshot().generation_jobs, 0);
assert_eq!(
state.worker.read().await.state,
state.engine.worker.read().await.state,
crate::worker::WorkerState::Restarting
);
server.abort();
+1 -2
View File
@@ -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<T> = std::result::Result<T, Box<dyn Error>>;
type Result<T> = std::result::Result<T, crate::BoxError>;
/// 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`).
+1 -2
View File
@@ -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<T> = std::result::Result<T, Box<dyn Error>>;
type Result<T> = std::result::Result<T, crate::BoxError>;
const FILES: &[&str] = &[
"dense.bin",
"index.txt",
+1 -2
View File
@@ -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<T> = std::result::Result<T, Box<dyn Error>>;
type Result<T> = std::result::Result<T, crate::BoxError>;
struct Shard {
path: PathBuf,
+29
View File
@@ -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<dyn Port>`, 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<Box<dyn std::future::Future<Output = T> + 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};
+24
View File
@@ -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<dyn Clock>;
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()
}
}
+25
View File
@@ -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<dyn EngineClient>;
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<Duration>,
) -> 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;
}
+13
View File
@@ -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;
+44
View File
@@ -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<Duration>,
}
impl ManualClock {
/// Starts at `unix_secs` seconds after the epoch.
pub fn new(unix_secs: u64) -> Arc<Self> {
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()
}
}
+131
View File
@@ -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<Event>),
/// 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<Event> = 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<VecDeque<Script>>,
seen: Mutex<Vec<Generate>>,
budgets: Mutex<Vec<Option<Duration>>>,
capacity: usize,
}
impl ScriptedEngine {
pub fn new(scripts: Vec<Script>) -> Arc<Self> {
Arc::new(Self {
scripts: Mutex::new(scripts.into()),
seen: Mutex::new(Vec::new()),
budgets: Mutex::new(Vec::new()),
capacity: 16,
})
}
/// The requests the engine took, oldest first.
pub fn requests(&self) -> Vec<Generate> {
self.seen.lock().unwrap().clone()
}
/// The queue budget of every submit, including refused ones.
pub fn budgets(&self) -> Vec<Option<Duration>> {
self.budgets.lock().unwrap().clone()
}
fn next(&self) -> Script {
let script = self.scripts.lock().unwrap().pop_front();
script.unwrap_or_else(|| Script::tokens(&[]))
}
}
impl EngineClient for ScriptedEngine {
fn submit(
&self,
mut command: GenerationCommand,
budget: Option<Duration>,
) -> BoxFuture<'_, Result<(), Error>> {
self.budgets.lock().unwrap().push(budget);
let script = self.next();
Box::pin(async move {
if let Script::Refuse(error) = script {
return Err(error);
}
self.seen.lock().unwrap().push(command.request.clone());
let result = command.result.take();
let _activity = command.activity.take();
answer(result, script);
Ok(())
})
}
fn queue_capacity(&self) -> usize {
self.capacity
}
fn queue_used(&self) -> usize {
0
}
}
fn answer(result: GenerationResult, script: Script) {
match (result, script) {
(GenerationResult::Buffered(sender), Script::Events(events)) => {
let _ = sender.send(Ok(events));
}
(GenerationResult::Buffered(sender), Script::Fail(message)) => {
let _ = sender.send(Err(message));
}
// The reader starts after `submit` returned: feed the stream from a task, not from the submit.
(GenerationResult::Streaming(sender), Script::Events(events)) => {
tokio::spawn(async move {
for event in events {
let _ = sender.send(Ok(event)).await;
}
});
}
(GenerationResult::Streaming(sender), Script::Fail(message)) => {
tokio::spawn(async move {
let _ = sender.send(Err(message)).await;
});
}
_ => {}
}
}
+92
View File
@@ -0,0 +1,92 @@
use std::{
collections::HashMap,
sync::{
Mutex,
atomic::{AtomicBool, Ordering},
},
};
use serde_json::{Value, json};
use crate::ports::{BoxFuture, ResponseStore, response_store::InputItemsQuery};
/// A response store that keeps everything and persists nothing. It lists the inserts, so a test can see whether a
/// request was stored.
/// Model, transcript and response object of a stored response.
type Stored = (String, Vec<Value>, Value);
#[derive(Default)]
pub struct MemoryResponseStore {
entries: Mutex<HashMap<String, Stored>>,
inserted: Mutex<Vec<String>>,
failing: AtomicBool,
}
impl MemoryResponseStore {
/// Ids in the order they were inserted.
pub fn inserted(&self) -> Vec<String> {
self.inserted.lock().unwrap().clone()
}
/// Make every insert fail, as a full disk would.
pub fn fail_inserts(&self) {
self.failing.store(true, Ordering::Relaxed);
}
}
impl ResponseStore for MemoryResponseStore {
fn transcript<'a>(&'a self, id: &'a str, model: &'a str) -> BoxFuture<'a, Option<Vec<Value>>> {
Box::pin(async move {
let entries = self.entries.lock().unwrap();
let (stored_model, transcript, _) = entries.get(id)?;
(stored_model == model).then(|| transcript.clone())
})
}
fn response<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Option<Value>> {
Box::pin(async move { Some(self.entries.lock().unwrap().get(id)?.2.clone()) })
}
fn input_page<'a>(
&'a self,
id: &'a str,
_query: &'a InputItemsQuery,
) -> BoxFuture<'a, Option<Result<Value, &'static str>>> {
Box::pin(async move {
let entries = self.entries.lock().unwrap();
let (_, transcript, _) = entries.get(id)?;
Some(Ok(json!({"object": "list", "data": transcript})))
})
}
fn insert<'a>(
&'a self,
id: &'a str,
model: &'a str,
input: &'a Value,
response: &'a Value,
) -> BoxFuture<'a, Result<(), &'static str>> {
Box::pin(async move {
if self.failing.load(Ordering::Relaxed) {
return Err("fake storage failure");
}
let mut transcript = input.as_array().cloned().unwrap_or_default();
if let Some(text) = input.as_str() {
transcript.push(json!({"role": "user", "content": text}));
}
transcript.extend(response["output"].as_array().cloned().unwrap_or_default());
let entry = (model.to_owned(), transcript, response.clone());
self.entries.lock().unwrap().insert(id.to_owned(), entry);
self.inserted.lock().unwrap().push(id.to_owned());
Ok(())
})
}
fn count(&self) -> BoxFuture<'_, usize> {
Box::pin(async move { self.entries.lock().unwrap().len() })
}
fn delete<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Result<bool, &'static str>> {
Box::pin(async move { Ok(self.entries.lock().unwrap().remove(id).is_some()) })
}
}
+82
View File
@@ -0,0 +1,82 @@
use std::sync::Mutex;
use serde_json::{Value, json};
use crate::{
mcp::{CallOutput, Cancel, McpError},
ports::{BoxFuture, ToolHub},
};
/// A hub with a fixed tool list whose calls echo their arguments.
pub struct FakeToolHub {
tools: Vec<String>,
calls: Mutex<Vec<(String, Value)>>,
}
impl FakeToolHub {
pub fn new(tools: &[&str]) -> Self {
Self {
tools: tools.iter().map(|name| (*name).to_owned()).collect(),
calls: Mutex::new(Vec::new()),
}
}
pub fn calls(&self) -> Vec<(String, Value)> {
self.calls.lock().unwrap().clone()
}
}
impl ToolHub for FakeToolHub {
fn status(&self) -> BoxFuture<'_, Value> {
Box::pin(async move {
let tools: Vec<Value> = self
.tools
.iter()
.map(|name| json!({"name": name}))
.collect();
let server = json!({"name": "fake", "status": "ready", "tools": tools});
json!({"servers": [server], "tools": self.tools.len()})
})
}
fn template_tools<'a>(&'a self, exclude: &'a [String]) -> BoxFuture<'a, Vec<Value>> {
Box::pin(async move {
let kept = self.tools.iter().filter(|name| !exclude.contains(name));
kept.map(|name| json!({"name": name, "description": "", "parameters": {}}))
.collect()
})
}
fn call<'a>(
&'a self,
name: &'a str,
arguments: Value,
_cancel: Option<Cancel>,
) -> BoxFuture<'a, Result<CallOutput, McpError>> {
Box::pin(async move {
let known = self.tools.iter().any(|tool| tool == name);
let text = if known {
arguments.to_string()
} else {
format!("error: there is no tool named {name:?}")
};
self.calls
.lock()
.unwrap()
.push((name.to_owned(), arguments));
Ok(CallOutput {
ok: known,
chars: text.chars().count(),
text,
truncated: false,
ms: 0,
server: known.then(|| "fake".to_owned()),
tool: name.to_owned(),
})
})
}
fn close(&self) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
}
+72
View File
@@ -0,0 +1,72 @@
use std::{
path::PathBuf,
sync::{
Mutex,
atomic::{AtomicUsize, Ordering},
},
};
use crate::{
ports::{BoxFuture, VisionEncoder},
vision::{Encoded, Keep, VisionError},
};
/// An encoder that gives every picture the same number of image tokens and writes no file.
pub struct FakeVisionEncoder {
tokens: usize,
encoded: Mutex<Vec<String>>,
combined: AtomicUsize,
}
impl FakeVisionEncoder {
pub fn new(tokens_per_image: usize) -> Self {
Self {
tokens: tokens_per_image,
encoded: Mutex::new(Vec::new()),
combined: AtomicUsize::new(0),
}
}
/// The sources that were encoded, in order.
pub fn encoded(&self) -> Vec<String> {
self.encoded.lock().unwrap().clone()
}
pub fn combined(&self) -> usize {
self.combined.load(Ordering::Relaxed)
}
}
impl VisionEncoder for FakeVisionEncoder {
fn encode_all<'a>(
&'a self,
sources: &'a [String],
) -> BoxFuture<'a, Result<Vec<Encoded>, VisionError>> {
Box::pin(async move {
let mut encoded = self.encoded.lock().unwrap();
let mut out = Vec::new();
for source in sources {
if source.is_empty() {
return Err(VisionError::Invalid("empty image".into()));
}
encoded.push(source.clone());
out.push(Encoded {
path: PathBuf::from(format!("fake-{}.sve", encoded.len())),
tokens: self.tokens,
});
}
Ok(out)
})
}
fn combine<'a>(
&'a self,
_images: &'a [Encoded],
) -> BoxFuture<'a, Result<(PathBuf, Keep), VisionError>> {
Box::pin(async move {
let n = self.combined.fetch_add(1, Ordering::Relaxed);
let path = PathBuf::from(format!("fake-request-{n}.sve"));
Ok((path, Keep::default()))
})
}
}
+48
View File
@@ -0,0 +1,48 @@
//! Stored Responses (`store: true`, `previous_response_id`, `GET/DELETE /v1/responses/{id}`).
use serde_json::Value;
use super::BoxFuture;
/// `after`, `limit` and `order` of `GET /v1/responses/{id}/input_items`.
#[derive(Default, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InputItemsQuery {
pub after: Option<String>,
pub limit: Option<usize>,
pub order: Option<String>,
}
/// What `AppState` holds.
pub type SharedResponseStore = std::sync::Arc<dyn ResponseStore>;
/// Errors are fixed strings: a payload is never part of an error.
pub trait ResponseStore: Send + Sync {
/// The transcript (input and output items) of a stored response of this `model`, for a follow-up request.
fn transcript<'a>(&'a self, id: &'a str, model: &'a str) -> BoxFuture<'a, Option<Vec<Value>>>;
/// The stored response object.
fn response<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Option<Value>>;
/// One page of the input items of a stored response: `None` when it is unknown, `Err` for a bad cursor.
fn input_page<'a>(
&'a self,
id: &'a str,
query: &'a InputItemsQuery,
) -> BoxFuture<'a, Option<Result<Value, &'static str>>>;
/// Remember a finished response and, when the store is durable, commit it before returning.
fn insert<'a>(
&'a self,
id: &'a str,
model: &'a str,
input: &'a Value,
response: &'a Value,
) -> BoxFuture<'a, Result<(), &'static str>>;
/// How many responses are kept.
fn count(&self) -> BoxFuture<'_, usize>;
/// Forget a response: `Ok(false)` when it was not there.
fn delete<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Result<bool, &'static str>>;
}
+28
View File
@@ -0,0 +1,28 @@
//! The MCP servers the operator configured, as the gateway uses them: status, tool list, one tool call.
use serde_json::Value;
use super::BoxFuture;
use crate::mcp::{CallOutput, Cancel, McpError};
/// What `AppState` holds.
pub type SharedToolHub = std::sync::Arc<dyn ToolHub>;
pub trait ToolHub: Send + Sync {
/// `GET /mcp`: every server, its state and its tools.
fn status(&self) -> BoxFuture<'_, Value>;
/// The tools in the chat template's form; `exclude` names the tools the request brought itself.
fn template_tools<'a>(&'a self, exclude: &'a [String]) -> BoxFuture<'a, Vec<Value>>;
/// Run one tool. Tool errors are text in the output; only a stop (`cancel`) is an `Err`.
fn call<'a>(
&'a self,
name: &'a str,
arguments: Value,
cancel: Option<Cancel>,
) -> BoxFuture<'a, Result<CallOutput, McpError>>;
/// Stop every server.
fn close(&self) -> BoxFuture<'_, ()>;
}
+24
View File
@@ -0,0 +1,24 @@
//! The resident image encoder, as the Responses handler uses it.
use std::path::PathBuf;
use super::BoxFuture;
use crate::vision::{Encoded, Keep, VisionError};
/// What `AppState` holds.
pub type SharedVisionEncoder = std::sync::Arc<dyn VisionEncoder>;
pub trait VisionEncoder: Send + Sync {
/// Encode the pictures in turn, while the engine is idle: the engine and the encoder are separate processes that
/// must not use the GPU at the same time.
fn encode_all<'a>(
&'a self,
sources: &'a [String],
) -> BoxFuture<'a, Result<Vec<Encoded>, VisionError>>;
/// The embeddings file of one request: the encoded pictures in prompt order, and the guard that removes it.
fn combine<'a>(
&'a self,
images: &'a [Encoded],
) -> BoxFuture<'a, Result<(PathBuf, Keep), VisionError>>;
}
+2 -393
View File
@@ -28,399 +28,6 @@ struct Series {
label: Option<(&'static str, &'static str)>,
}
const SERIES: &[Series] = &[
counter(
"leleka_generations_started_total",
"Generations admitted to the engine.",
"/generation/started",
1.0,
),
counter(
"leleka_generations_completed_total",
"Generations that ended with a DONE other than cancel.",
"/generation/completed",
1.0,
),
counter(
"leleka_generations_cancelled_total",
"Generations cancelled or abandoned by the client.",
"/generation/cancelled",
1.0,
),
counter(
"leleka_generations_failed_total",
"Admitted generations that ended without a DONE.",
"/generation/failed_or_interrupted",
1.0,
),
counter(
"leleka_prompt_tokens_total",
"Prompt tokens of settled generations.",
"/totals/prompt_tokens",
1.0,
),
counter(
"leleka_prompt_tokens_reused_total",
"Prompt tokens served from a cache.",
"/totals/reused",
1.0,
),
counter(
"leleka_generated_tokens_total",
"Tokens generated by settled generations.",
"/totals/output_tokens",
1.0,
),
counter(
"leleka_prefill_seconds_total",
"Engine time spent reading prompts.",
"/totals/prompt_ms",
1e-3,
),
counter(
"leleka_decode_seconds_total",
"Engine time spent generating tokens.",
"/totals/decode_ms",
1e-3,
),
counter(
"leleka_draft_tokens_offered_total",
"Speculative draft tokens offered.",
"/totals/drafts_offered",
1.0,
),
counter(
"leleka_draft_tokens_accepted_total",
"Speculative draft tokens accepted.",
"/totals/drafts_accepted",
1.0,
),
counter(
"leleka_memory_gate_rejections_total",
"Requests refused up front for host memory pressure.",
"/memory/gate_rejections",
1.0,
),
gauge(
"leleka_up",
"1 when the engine is loaded and accepting generations.",
"/up",
1.0,
),
gauge(
"leleka_generation_active",
"1 while a generation runs.",
"/live/active",
1.0,
),
gauge(
"leleka_generation_elapsed_seconds",
"Seconds the running generation has been active.",
"/live/elapsed_s",
1.0,
),
gauge(
"leleka_requests_queued",
"Generations waiting for the engine.",
"/live/queued",
1.0,
),
gauge(
"leleka_queue_used",
"Commands in the bounded generation channel.",
"/queue_used",
1.0,
),
gauge(
"leleka_queue_capacity",
"Capacity of the generation channel.",
"/queue_capacity",
1.0,
),
gauge(
"leleka_context_max_tokens",
"Context window the engine serves, in tokens.",
"/engine/max_context",
1.0,
),
gauge(
"leleka_context_live_tokens",
"Tokens in the session context (prompt plus output).",
"/telemetry/context/live_tokens",
1.0,
),
gauge(
"leleka_context_used_percent",
"Share of the context window in use.",
"/telemetry/context/used_pct",
1.0,
),
gauge(
"leleka_gpu_utilization_percent",
"Share of the last sample period in which a kernel ran.",
"/hardware/gpu_util",
1.0,
),
gauge(
"leleka_gpu_memory_utilization_percent",
"Share of the period the memory interface was busy.",
"/hardware/gpu_mem_util",
1.0,
),
gauge(
"leleka_gpu_memory_used_bytes",
"Device memory in use.",
"/hardware/gpu_mem_used",
1.0,
),
gauge(
"leleka_gpu_memory_total_bytes",
"Device memory installed.",
"/hardware/gpu_mem_total",
1.0,
),
gauge(
"leleka_gpu_temperature_celsius",
"GPU core temperature.",
"/hardware/gpu_temp",
1.0,
),
gauge(
"leleka_gpu_power_watts",
"GPU board power draw.",
"/hardware/gpu_power",
1.0,
),
gauge(
"leleka_gpu_sm_clock_megahertz",
"GPU SM clock.",
"/hardware/gpu_sm_clock_mhz",
1.0,
),
gauge(
"leleka_host_memory_used_bytes",
"Host RAM in use (total minus available).",
"/hardware/ram_used",
1.0,
),
gauge(
"leleka_host_memory_total_bytes",
"Host RAM installed.",
"/hardware/ram_total",
1.0,
),
gauge(
"leleka_host_swap_used_bytes",
"Swap in use.",
"/hardware/swap_used",
1.0,
),
gauge(
"leleka_engine_resident_bytes",
"Resident set of the engine process.",
"/hardware/ram_process_rss",
1.0,
),
gauge(
"leleka_engine_pinned_bytes",
"Page-locked memory of the engine process.",
"/hardware/ram_process_pinned",
1.0,
),
gauge(
"leleka_host_cpu_busy_percent",
"Busy share of all CPUs.",
"/hardware/cpu",
1.0,
),
gauge(
"leleka_engine_cpu_busy_cores",
"CPU cores worth of time the engine used.",
"/hardware/cpu_process_cores",
1.0,
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s",
("window", "live"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_last",
("window", "last"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s_mean",
("window", "average"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_lifetime",
("window", "lifetime"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_last",
("window", "last"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/hardware/prefill_tok_s_mean",
("window", "average"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_lifetime",
("window", "lifetime"),
),
gauge(
"leleka_gpu_memory_clock_megahertz",
"GPU memory clock.",
"/telemetry/gpu/mem_clock_mhz",
1.0,
),
gauge(
"leleka_gpu_pcie_receive_bytes_per_second",
"PCIe traffic into the GPU over the last sampling window.",
"/telemetry/gpu/pcie_rx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_pcie_transmit_bytes_per_second",
"PCIe traffic out of the GPU over the last sampling window.",
"/telemetry/gpu/pcie_tx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_throttle_reasons",
"NVML clocks-throttle-reasons bit mask (0: the clocks are not held down).",
"/telemetry/gpu/throttle_reasons",
1.0,
),
gauge(
"leleka_engine_uptime_seconds",
"Seconds since the engine process started.",
"/telemetry/uptime_s",
1.0,
),
gauge(
"leleka_api_uptime_seconds",
"Seconds since this API process started.",
"/api_uptime_s",
1.0,
),
gauge(
"leleka_service_uptime_seconds",
"Seconds since the supervisor started.",
"/supervisor/uptime_s",
1.0,
),
counter(
"leleka_engine_restarts_total",
"Engine restarts by the supervisor since the service started (crash, hang, failed restart).",
"/supervisor/restarts_total",
1.0,
),
counter(
"leleka_spec_rounds_total",
"Speculative verify rounds the engine ran.",
"/telemetry/spec/rounds",
1.0,
),
counter(
"leleka_spec_tokens_total",
"Tokens those rounds committed.",
"/telemetry/spec/tokens",
1.0,
),
gauge(
"leleka_spec_tokens_per_round",
"Committed tokens per verify round, lifetime (1 means drafting gains nothing).",
"/telemetry/spec/tokens_per_round",
1.0,
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/vram_entries",
("tier", "vram"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/pcie_entries",
("tier", "pcie"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/cpu_entries",
("tier", "cpu"),
),
gauge(
"leleka_expert_tier_vram_ratio",
"Share of expert entries served from the VRAM tier (the tier's hit rate).",
"/telemetry/expert_tier/vram_ratio",
1.0,
),
counter(
"leleka_expert_tier_swaps_total",
"Experts swapped in or out of the VRAM tier by adaptation.",
"/telemetry/expert_tier/swaps",
1.0,
),
counter(
"leleka_nan_guard_healed_total",
"Non-finite verify windows that a retry fixed.",
"/telemetry/nan_guard/healed_windows",
1.0,
),
counter(
"leleka_nan_guard_unhealed_total",
"Non-finite verify windows given up on.",
"/telemetry/nan_guard/unhealed_windows",
1.0,
),
gauge(
"leleka_prefix_cache_requests",
"Requests the prefix cache has seen.",
"/telemetry/cache/requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_requests",
"Requests that reused a checkpoint.",
"/telemetry/cache/hit_requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_ratio",
"Share of requests that reused a checkpoint.",
"/telemetry/cache/hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_token_hit_ratio",
"Share of prompt tokens served from a checkpoint.",
"/telemetry/cache/token_hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_reused_tokens",
"Prompt tokens reused since the engine started.",
"/telemetry/cache/reused_tokens",
1.0,
),
];
/// The phase the engine reports, as a one-hot gauge (`idle`, `prefill`, `decode`).
const PHASES: [&str; 3] = ["idle", "prefill", "decode"];
@@ -436,6 +43,8 @@ const THROTTLE_REASONS: [(u64, &str); 5] = [
#[cfg(test)]
mod tests;
mod series;
use series::SERIES;
mod counter;
#[allow(unused_imports)]
pub use counter::*;
+396
View File
@@ -0,0 +1,396 @@
//! The series table: every Prometheus metric the control plane exposes and where its value comes from.
use super::*;
pub(super) const SERIES: &[Series] = &[
counter(
"leleka_generations_started_total",
"Generations admitted to the engine.",
"/generation/started",
1.0,
),
counter(
"leleka_generations_completed_total",
"Generations that ended with a DONE other than cancel.",
"/generation/completed",
1.0,
),
counter(
"leleka_generations_cancelled_total",
"Generations cancelled or abandoned by the client.",
"/generation/cancelled",
1.0,
),
counter(
"leleka_generations_failed_total",
"Admitted generations that ended without a DONE.",
"/generation/failed_or_interrupted",
1.0,
),
counter(
"leleka_prompt_tokens_total",
"Prompt tokens of settled generations.",
"/totals/prompt_tokens",
1.0,
),
counter(
"leleka_prompt_tokens_reused_total",
"Prompt tokens served from a cache.",
"/totals/reused",
1.0,
),
counter(
"leleka_generated_tokens_total",
"Tokens generated by settled generations.",
"/totals/output_tokens",
1.0,
),
counter(
"leleka_prefill_seconds_total",
"Engine time spent reading prompts.",
"/totals/prompt_ms",
1e-3,
),
counter(
"leleka_decode_seconds_total",
"Engine time spent generating tokens.",
"/totals/decode_ms",
1e-3,
),
counter(
"leleka_draft_tokens_offered_total",
"Speculative draft tokens offered.",
"/totals/drafts_offered",
1.0,
),
counter(
"leleka_draft_tokens_accepted_total",
"Speculative draft tokens accepted.",
"/totals/drafts_accepted",
1.0,
),
counter(
"leleka_memory_gate_rejections_total",
"Requests refused up front for host memory pressure.",
"/memory/gate_rejections",
1.0,
),
gauge(
"leleka_up",
"1 when the engine is loaded and accepting generations.",
"/up",
1.0,
),
gauge(
"leleka_generation_active",
"1 while a generation runs.",
"/live/active",
1.0,
),
gauge(
"leleka_generation_elapsed_seconds",
"Seconds the running generation has been active.",
"/live/elapsed_s",
1.0,
),
gauge(
"leleka_requests_queued",
"Generations waiting for the engine.",
"/live/queued",
1.0,
),
gauge(
"leleka_queue_used",
"Commands in the bounded generation channel.",
"/queue_used",
1.0,
),
gauge(
"leleka_queue_capacity",
"Capacity of the generation channel.",
"/queue_capacity",
1.0,
),
gauge(
"leleka_context_max_tokens",
"Context window the engine serves, in tokens.",
"/engine/max_context",
1.0,
),
gauge(
"leleka_context_live_tokens",
"Tokens in the session context (prompt plus output).",
"/telemetry/context/live_tokens",
1.0,
),
gauge(
"leleka_context_used_percent",
"Share of the context window in use.",
"/telemetry/context/used_pct",
1.0,
),
gauge(
"leleka_gpu_utilization_percent",
"Share of the last sample period in which a kernel ran.",
"/hardware/gpu_util",
1.0,
),
gauge(
"leleka_gpu_memory_utilization_percent",
"Share of the period the memory interface was busy.",
"/hardware/gpu_mem_util",
1.0,
),
gauge(
"leleka_gpu_memory_used_bytes",
"Device memory in use.",
"/hardware/gpu_mem_used",
1.0,
),
gauge(
"leleka_gpu_memory_total_bytes",
"Device memory installed.",
"/hardware/gpu_mem_total",
1.0,
),
gauge(
"leleka_gpu_temperature_celsius",
"GPU core temperature.",
"/hardware/gpu_temp",
1.0,
),
gauge(
"leleka_gpu_power_watts",
"GPU board power draw.",
"/hardware/gpu_power",
1.0,
),
gauge(
"leleka_gpu_sm_clock_megahertz",
"GPU SM clock.",
"/hardware/gpu_sm_clock_mhz",
1.0,
),
gauge(
"leleka_host_memory_used_bytes",
"Host RAM in use (total minus available).",
"/hardware/ram_used",
1.0,
),
gauge(
"leleka_host_memory_total_bytes",
"Host RAM installed.",
"/hardware/ram_total",
1.0,
),
gauge(
"leleka_host_swap_used_bytes",
"Swap in use.",
"/hardware/swap_used",
1.0,
),
gauge(
"leleka_engine_resident_bytes",
"Resident set of the engine process.",
"/hardware/ram_process_rss",
1.0,
),
gauge(
"leleka_engine_pinned_bytes",
"Page-locked memory of the engine process.",
"/hardware/ram_process_pinned",
1.0,
),
gauge(
"leleka_host_cpu_busy_percent",
"Busy share of all CPUs.",
"/hardware/cpu",
1.0,
),
gauge(
"leleka_engine_cpu_busy_cores",
"CPU cores worth of time the engine used.",
"/hardware/cpu_process_cores",
1.0,
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s",
("window", "live"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_last",
("window", "last"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/hardware/tok_s_mean",
("window", "average"),
),
labelled(
"leleka_decode_tokens_per_second",
"Decode throughput.",
"/telemetry/throughput/decode_tok_s_lifetime",
("window", "lifetime"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_last",
("window", "last"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/hardware/prefill_tok_s_mean",
("window", "average"),
),
labelled(
"leleka_prefill_tokens_per_second",
"Prefill throughput over newly read tokens.",
"/telemetry/throughput/prefill_tok_s_lifetime",
("window", "lifetime"),
),
gauge(
"leleka_gpu_memory_clock_megahertz",
"GPU memory clock.",
"/telemetry/gpu/mem_clock_mhz",
1.0,
),
gauge(
"leleka_gpu_pcie_receive_bytes_per_second",
"PCIe traffic into the GPU over the last sampling window.",
"/telemetry/gpu/pcie_rx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_pcie_transmit_bytes_per_second",
"PCIe traffic out of the GPU over the last sampling window.",
"/telemetry/gpu/pcie_tx_kb_s",
1024.0,
),
gauge(
"leleka_gpu_throttle_reasons",
"NVML clocks-throttle-reasons bit mask (0: the clocks are not held down).",
"/telemetry/gpu/throttle_reasons",
1.0,
),
gauge(
"leleka_engine_uptime_seconds",
"Seconds since the engine process started.",
"/telemetry/uptime_s",
1.0,
),
gauge(
"leleka_api_uptime_seconds",
"Seconds since this API process started.",
"/api_uptime_s",
1.0,
),
gauge(
"leleka_service_uptime_seconds",
"Seconds since the supervisor started.",
"/supervisor/uptime_s",
1.0,
),
counter(
"leleka_engine_restarts_total",
"Engine restarts by the supervisor since the service started (crash, hang, failed restart).",
"/supervisor/restarts_total",
1.0,
),
counter(
"leleka_spec_rounds_total",
"Speculative verify rounds the engine ran.",
"/telemetry/spec/rounds",
1.0,
),
counter(
"leleka_spec_tokens_total",
"Tokens those rounds committed.",
"/telemetry/spec/tokens",
1.0,
),
gauge(
"leleka_spec_tokens_per_round",
"Committed tokens per verify round, lifetime (1 means drafting gains nothing).",
"/telemetry/spec/tokens_per_round",
1.0,
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/vram_entries",
("tier", "vram"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/pcie_entries",
("tier", "pcie"),
),
labelled_counter(
"leleka_expert_tier_entries_total",
"Expert entries served, by where they were found.",
"/telemetry/expert_tier/cpu_entries",
("tier", "cpu"),
),
gauge(
"leleka_expert_tier_vram_ratio",
"Share of expert entries served from the VRAM tier (the tier's hit rate).",
"/telemetry/expert_tier/vram_ratio",
1.0,
),
counter(
"leleka_expert_tier_swaps_total",
"Experts swapped in or out of the VRAM tier by adaptation.",
"/telemetry/expert_tier/swaps",
1.0,
),
counter(
"leleka_nan_guard_healed_total",
"Non-finite verify windows that a retry fixed.",
"/telemetry/nan_guard/healed_windows",
1.0,
),
counter(
"leleka_nan_guard_unhealed_total",
"Non-finite verify windows given up on.",
"/telemetry/nan_guard/unhealed_windows",
1.0,
),
gauge(
"leleka_prefix_cache_requests",
"Requests the prefix cache has seen.",
"/telemetry/cache/requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_requests",
"Requests that reused a checkpoint.",
"/telemetry/cache/hit_requests",
1.0,
),
gauge(
"leleka_prefix_cache_hit_ratio",
"Share of requests that reused a checkpoint.",
"/telemetry/cache/hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_token_hit_ratio",
"Share of prompt tokens served from a checkpoint.",
"/telemetry/cache/token_hit_ratio",
1.0,
),
gauge(
"leleka_prefix_cache_reused_tokens",
"Prompt tokens reused since the engine started.",
"/telemetry/cache/reused_tokens",
1.0,
),
];
+36 -3
View File
@@ -1,5 +1,5 @@
//! Optional queue deadline. Claim and expiration have one atomic winner.
use crate::worker::GenerationCommand;
use crate::{adapters::SystemClock, ports::SharedClock, worker::GenerationCommand};
use std::sync::{
Arc,
atomic::{AtomicU8, Ordering},
@@ -16,6 +16,7 @@ const EXPIRED: u8 = 2;
pub struct Ticket {
deadline: Instant,
clock: SharedClock,
state: Arc<AtomicU8>,
started: oneshot::Sender<()>,
}
@@ -31,7 +32,7 @@ impl Ticket {
// Check after the CAS: a thread may have been preempted across the
// deadline before claiming. The requester waits for acknowledgment
// after losing its expiry CAS, so a late claimant can still refuse.
if Instant::now() >= self.deadline {
if self.clock.now() >= self.deadline {
self.state.store(EXPIRED, Ordering::Release);
return false;
}
@@ -46,19 +47,31 @@ pub enum Error {
Closed,
}
/// [`enqueue_with`] on the system clock.
pub async fn enqueue(
sender: &mpsc::Sender<GenerationCommand>,
command: GenerationCommand,
budget: Option<Duration>,
) -> Result<(), Error> {
enqueue_with(sender, command, budget, SystemClock::shared()).await
}
/// Queue a command; with a `budget` it must be claimed by the worker before `clock.now() + budget`.
pub async fn enqueue_with(
sender: &mpsc::Sender<GenerationCommand>,
mut command: GenerationCommand,
budget: Option<Duration>,
clock: SharedClock,
) -> Result<(), Error> {
let Some(budget) = budget else {
return sender.send(command).await.map_err(|_| Error::Closed);
};
let deadline = Instant::now() + budget;
let deadline = clock.now() + budget;
let state = Arc::new(AtomicU8::new(QUEUED));
let (started, mut received) = oneshot::channel();
command.queue = Some(Ticket {
deadline,
clock,
state: state.clone(),
started,
});
@@ -170,6 +183,7 @@ mod tests {
assert!(
!Ticket {
deadline,
clock: SystemClock::shared(),
state,
started
}
@@ -177,4 +191,23 @@ mod tests {
);
}
}
#[tokio::test]
async fn queue_deadline_follows_the_injected_clock() {
let clock = crate::ports::fakes::ManualClock::new(0);
let (sender, mut pending) = mpsc::channel(1);
let (job, _result) = command();
let submit_clock = clock.clone();
let submit = tokio::spawn(async move {
enqueue_with(&sender, job, Some(Duration::from_secs(30)), submit_clock).await
});
let ticket = pending.recv().await.unwrap().queue.unwrap();
// 31 s pass on the injected clock only; no real time does.
clock.advance(Duration::from_secs(31));
assert!(
!ticket.claim(),
"a claim after the deadline of the injected clock must be refused"
);
assert_eq!(submit.await.unwrap(), Err(Error::Expired));
}
}
+4 -4
View File
@@ -185,9 +185,9 @@ mod tests;
mod endpoint_index;
#[allow(unused_imports)]
pub use endpoint_index::*;
mod impl_obshandle;
mod obs_handle;
#[allow(unused_imports)]
pub use impl_obshandle::*;
mod note_engine_attached;
pub use obs_handle::*;
mod engine_counters;
#[allow(unused_imports)]
pub use note_engine_attached::*;
pub use engine_counters::*;
+4 -11
View File
@@ -19,13 +19,13 @@ use std::{
atomic::{AtomicU64, Ordering},
},
task::{Context, Poll},
time::{SystemTime, UNIX_EPOCH},
};
use tokio::sync::{RwLock, mpsc, oneshot};
use crate::{
app::AppState,
codec::{Family, TextCodec, decode_all},
ports::{SharedClock, SharedResponseStore, response_store::InputItemsQuery},
prompt::{self, Effort, Message, Part, Role},
response_tools::Catalog,
tokenizer::{LiteralMarks, Tokenizer},
@@ -62,14 +62,6 @@ struct StoredResponse {
bytes: usize,
}
#[derive(Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct InputItemsQuery {
after: Option<String>,
limit: Option<usize>,
order: Option<String>,
}
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CreateRequest {
@@ -178,7 +170,10 @@ struct Owned {
parts: Option<Vec<Part>>,
}
mod history_adapter;
pub use history_adapter::HistoryResponseStore;
mod stream;
pub(crate) use stream::StreamEnv;
use stream::*;
#[derive(Clone, Deserialize)]
@@ -226,8 +221,6 @@ use set_tool_call_recovery_fn::resource_not_found;
#[allow(unused_imports)]
pub use set_tool_call_recovery_fn::set_tool_call_recovery;
#[allow(unused_imports)]
use set_tool_call_recovery_fn::store_response;
#[allow(unused_imports)]
use set_tool_call_recovery_fn::tool_options;
mod resource_query_error_fn;
#[allow(unused_imports)]
+27 -29
View File
@@ -14,7 +14,7 @@ pub async fn create(
if let Err(response) = crate::server_api::ensure_loaded(&state).await {
return *response;
}
if state.worker.read().await.state != WorkerState::Ready {
if state.engine.worker.read().await.state != WorkerState::Ready {
return api_error(
StatusCode::SERVICE_UNAVAILABLE,
"server_error",
@@ -25,10 +25,10 @@ pub async fn create(
}
// The engine's memory governor says the host is at its hard floor: refuse now, with Retry-After, instead of queueing
// work that would push it into swap or the OOM killer (`docs/memory-safety.md`).
if let Some(closed) = state.memory.closed() {
if let Some(closed) = state.model.memory.closed() {
return crate::memory_view::refusal_response(closed.retry_after_secs, &closed.reason);
}
let (Some(tokenizer), Some(generation)) = (&state.tokenizer, &state.generation) else {
let (Some(tokenizer), Some(engine)) = (&state.model.tokenizer, &state.engine.client) else {
return api_error(
StatusCode::NOT_IMPLEMENTED,
"server_error",
@@ -59,7 +59,7 @@ pub async fn create(
);
}
}
request.apply_defaults(&state.settings);
request.apply_defaults(&state.services.settings);
if tokenizer.family() == Family::GptOss {
request.top_k = None;
request.min_p = None;
@@ -78,7 +78,7 @@ pub async fn create(
Err(error) => return *error,
};
let (max_context, output_cap, text_level_engine) = {
let worker = state.worker.read().await;
let worker = state.engine.worker.read().await;
(
worker.max_context,
worker.output_cap.unwrap_or(u32::MAX),
@@ -191,17 +191,17 @@ pub async fn create(
if request.stream {
let (events, received) = mpsc::channel(16);
let enqueue_span = crate::stage_trace::span("enqueue");
let enqueued = crate::queue::enqueue(
generation,
GenerationCommand {
queue: None,
activity: Some(state.lifecycle.generation()),
request: generate,
result: GenerationResult::Streaming(events),
},
state.queue_timeout,
)
.await;
let enqueued = engine
.submit(
GenerationCommand {
queue: None,
activity: Some(state.lifecycle.generation()),
request: generate,
result: GenerationResult::Streaming(events),
},
state.engine.queue_timeout,
)
.await;
drop(enqueue_span);
if let Err(error) = enqueued {
return queue_error(error);
@@ -210,7 +210,10 @@ pub async fn create(
request,
tokenizer.clone(),
received,
Some(state.response_history.clone()),
StreamEnv {
store: Some(state.services.responses.clone()),
clock: state.services.clock.clone(),
},
);
}
let (result, received) = oneshot::channel();
@@ -220,7 +223,7 @@ pub async fn create(
request: generate,
result: GenerationResult::Buffered(result),
};
if let Err(error) = crate::queue::enqueue(generation, command, state.queue_timeout).await {
if let Err(error) = engine.submit(command, state.engine.queue_timeout).await {
return queue_error(error);
}
let events = match received.await {
@@ -314,9 +317,7 @@ pub async fn create(
);
}
};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let now = state.services.clock.unix_time();
let id = format!(
"resp_{:x}_{:x}",
now.as_nanos(),
@@ -365,14 +366,11 @@ pub async fn create(
) {
Ok(trace) => {
if request.store != Some(false)
&& let Err(message) = store_response(
&state.response_history,
&id,
&request.model,
&request.input,
&trace.response,
)
.await
&& let Err(message) = state
.services
.responses
.insert(&id, &request.model, &request.input, &trace.response)
.await
{
return api_error(
StatusCode::INSUFFICIENT_STORAGE,
@@ -0,0 +1,93 @@
//! `ResponseStore` over the in-memory `ResponseHistory` and, when `response_history_dir` is set, its disk snapshot
//! (`history_store`). The history keeps the rules (64 entries, byte limit, snapshot checksum); this file only puts it
//! behind the port and decides which calls may block (a durable commit runs on the blocking pool).
use super::*;
use crate::ports::{
BoxFuture, ResponseStore, SharedResponseStore, response_store::InputItemsQuery,
};
pub struct HistoryResponseStore {
history: Arc<RwLock<ResponseHistory>>,
}
impl HistoryResponseStore {
pub fn new(history: ResponseHistory) -> Self {
Self {
history: Arc::new(RwLock::new(history)),
}
}
pub fn shared(history: ResponseHistory) -> SharedResponseStore {
Arc::new(Self::new(history))
}
}
impl ResponseStore for HistoryResponseStore {
fn transcript<'a>(&'a self, id: &'a str, model: &'a str) -> BoxFuture<'a, Option<Vec<Value>>> {
Box::pin(async move {
self.history
.read()
.await
.get(id, model)
.map(<[Value]>::to_vec)
})
}
fn response<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Option<Value>> {
Box::pin(async move {
let history = self.history.read().await;
history.entries.get(id).map(|entry| entry.response.clone())
})
}
fn input_page<'a>(
&'a self,
id: &'a str,
query: &'a InputItemsQuery,
) -> BoxFuture<'a, Option<Result<Value, &'static str>>> {
Box::pin(async move {
let history = self.history.read().await;
let entry = history.entries.get(id)?;
Some(entry.input_page(id, query))
})
}
fn insert<'a>(
&'a self,
id: &'a str,
model: &'a str,
input: &'a Value,
response: &'a Value,
) -> BoxFuture<'a, Result<(), &'static str>> {
Box::pin(async move {
let mut guard = self.history.clone().write_owned().await;
if guard.store.is_none() {
return guard.insert(id, model, input, response);
}
let (id, model, input, response) = (
id.to_owned(),
model.to_owned(),
input.clone(),
response.clone(),
);
tokio::task::spawn_blocking(move || guard.insert(&id, &model, &input, &response))
.await
.map_err(|_| "history storage task failed")?
})
}
fn count(&self) -> BoxFuture<'_, usize> {
Box::pin(async move { self.history.read().await.entries.len() })
}
fn delete<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Result<bool, &'static str>> {
Box::pin(async move {
let mut guard = self.history.clone().write_owned().await;
let target = id.to_owned();
tokio::task::spawn_blocking(move || guard.delete_committed(&target))
.await
.map_err(|_| "history storage task failed")?
})
}
}
@@ -217,11 +217,9 @@ pub(super) fn parse_request(
message,
)));
}
if state
.model
.as_ref()
.is_some_and(|model| model != &request.model && !state.aliases.contains(&request.model))
{
if state.model.name.as_ref().is_some_and(|model| {
model != &request.model && !state.model.aliases.contains(&request.model)
}) {
return Err(Box::new(api_error(
StatusCode::NOT_FOUND,
"invalid_request_error",
@@ -68,7 +68,7 @@ pub(super) fn reasoning_plan(
}
let budget = leleka_serving_policy::reasoning::parse_budget(
request.reasoning_budget_tokens.as_ref(),
state.settings.reasoning_budget_default(),
state.services.settings.reasoning_budget_default(),
)
.ok()??;
let wrap_up = tokenizer
@@ -23,13 +23,10 @@ pub async fn retrieve(
if let Some(error) = resource_query_error(query) {
return error;
}
let history = state.response_history.read().await;
let Some(entry) = history.entries.get(&id) else {
return resource_not_found();
};
let response = entry.response.clone();
drop(history);
Json(response).into_response()
match state.services.responses.response(&id).await {
Some(response) => Json(response).into_response(),
None => resource_not_found(),
}
}
impl InputItemsQuery {
@@ -152,15 +149,10 @@ pub async fn input_items(
Ok(options) => options,
Err(message) => return invalid(message),
};
let history = state.response_history.read().await;
let Some(entry) = history.entries.get(&id) else {
return resource_not_found();
};
let page = entry.input_page(&id, &options);
drop(history);
match page {
Ok(page) => Json(page).into_response(),
Err(message) => invalid(message),
match state.services.responses.input_page(&id, &options).await {
None => resource_not_found(),
Some(Ok(page)) => Json(page).into_response(),
Some(Err(message)) => invalid(message),
}
}
@@ -172,13 +164,10 @@ pub async fn delete(
if let Some(error) = resource_query_error(query) {
return error;
}
let mut guard = state.response_history.clone().write_owned().await;
let target = id.clone();
let result = tokio::task::spawn_blocking(move || guard.delete_committed(&target)).await;
match result {
Ok(Ok(true)) => (),
Ok(Ok(false)) => return resource_not_found(),
_ => {
match state.services.responses.delete(&id).await {
Ok(true) => (),
Ok(false) => return resource_not_found(),
Err(_) => {
return api_error(
StatusCode::INSUFFICIENT_STORAGE,
"server_error",
@@ -1,4 +1,4 @@
//! Moved out of the parent module by STRA-338: fn set_tool_call_recovery, fn tool_options, impl ResponseHistory, fn store_response, fn resource_not_found.
//! Moved out of the parent module by STRA-338: fn set_tool_call_recovery, fn tool_options, impl ResponseHistory, fn resource_not_found.
#[allow(unused_imports)]
use super::*;
@@ -210,28 +210,6 @@ impl ResponseHistory {
}
}
pub(super) async fn store_response(
history: &Arc<RwLock<ResponseHistory>>,
id: &str,
model: &str,
input: &Value,
response: &Value,
) -> Result<(), &'static str> {
let mut guard = history.clone().write_owned().await;
if guard.store.is_none() {
return guard.insert(id, model, input, response);
}
let (id, model, input, response) = (
id.to_owned(),
model.to_owned(),
input.clone(),
response.clone(),
);
tokio::task::spawn_blocking(move || guard.insert(&id, &model, &input, &response))
.await
.map_err(|_| "history storage task failed")?
}
pub(super) fn resource_not_found() -> Response {
api_error(
StatusCode::NOT_FOUND,
+24
View File
@@ -11,6 +11,30 @@ pub(super) use buffered::stream_live_buffered;
pub(super) use text::stream_live_text;
pub(super) use tools::stream_live_tools;
/// What a stream needs from outside once per response: where to store the finished response (`None`: nowhere) and
/// the clock its timestamps and id come from. Both are called at the start and the end of a stream, never per event.
#[derive(Clone)]
pub(crate) struct StreamEnv {
pub store: Option<SharedResponseStore>,
pub clock: SharedClock,
}
impl StreamEnv {
/// No store, system clock.
#[cfg(test)]
pub(crate) fn none() -> Self {
Self {
store: None,
clock: crate::adapters::SystemClock::shared(),
}
}
/// Seconds since the epoch and the same moment with nanoseconds, the form response ids use.
fn now(&self) -> std::time::Duration {
self.clock.unix_time()
}
}
pub(super) struct ResponseEventStream {
receiver: mpsc::Receiver<Value>,
}
+7 -17
View File
@@ -6,11 +6,9 @@ pub(in crate::responses) fn stream_live_buffered(
request: CreateRequest,
tokenizer: Arc<dyn TextCodec>,
mut source: mpsc::Receiver<Result<Event, String>>,
history: Option<Arc<RwLock<ResponseHistory>>>,
env: StreamEnv,
) -> Response {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let now = env.now();
let id = format!(
"resp_{:x}_{:x}",
now.as_nanos(),
@@ -137,10 +135,7 @@ pub(in crate::responses) fn stream_live_buffered(
},
&id,
created_at,
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
env.now().as_secs(),
done.finish == Finish::Length,
)
});
@@ -149,15 +144,10 @@ pub(in crate::responses) fn stream_live_buffered(
Ok(trace) => {
let _post_store = crate::stage_trace::span("post_store");
if request.store != Some(false)
&& let Some(history) = &history
&& let Err(error) = store_response(
history,
&id,
&request.model,
&request.input,
&trace.response,
)
.await
&& let Some(history) = &env.store
&& let Err(error) = history
.insert(&id, &request.model, &request.input, &trace.response)
.await
{
failure = Some(error.to_owned());
}
+9 -19
View File
@@ -6,17 +6,15 @@ pub(in crate::responses) fn stream_live_text(
request: CreateRequest,
tokenizer: Arc<dyn TextCodec>,
mut source: mpsc::Receiver<Result<Event, String>>,
history: Option<Arc<RwLock<ResponseHistory>>>,
env: StreamEnv,
) -> Response {
if is_structured(&request) || reasoning_enabled(&request, tokenizer.family()) {
return stream_live_buffered(request, tokenizer, source, history);
return stream_live_buffered(request, tokenizer, source, env);
}
if !request.tools.is_empty() {
return stream_live_tools(request, tokenizer, source, history);
return stream_live_tools(request, tokenizer, source, env);
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let now = env.now();
let id = format!(
"resp_{:x}_{:x}",
now.as_nanos(),
@@ -99,10 +97,7 @@ pub(in crate::responses) fn stream_live_text(
output.push_str(&delta);
if !send_stream_event(&sender, &mut sequence, "response.output_text.delta", json!({"response_id": id, "item_id": item_id, "output_index": 0, "content_index": 0, "delta": delta, "logprobs": []})).await { return; }
}
let completed_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let completed_at = env.now().as_secs();
let usage = Usage {
input_tokens: value.prompt_tokens,
output_tokens: value.generated,
@@ -122,15 +117,10 @@ pub(in crate::responses) fn stream_live_text(
) {
Ok(trace) => {
if request.store != Some(false)
&& let Some(history) = &history
&& let Err(error) = store_response(
history,
&id,
&request.model,
&request.input,
&trace.response,
)
.await
&& let Some(history) = &env.store
&& let Err(error) = history
.insert(&id, &request.model, &request.input, &trace.response)
.await
{
failure = Some(error.to_owned());
}
+12 -17
View File
@@ -126,11 +126,9 @@ pub(in crate::responses) fn stream_live_tools(
request: CreateRequest,
tokenizer: Arc<dyn TextCodec>,
mut source: mpsc::Receiver<Result<Event, String>>,
history: Option<Arc<RwLock<ResponseHistory>>>,
env: StreamEnv,
) -> Response {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let now = env.now();
let id = format!(
"resp_{:x}_{:x}",
now.as_nanos(),
@@ -259,10 +257,7 @@ pub(in crate::responses) fn stream_live_tools(
}
}
if failure.is_none() {
let completed_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let completed_at = env.now().as_secs();
let usage = Usage {
input_tokens: value.prompt_tokens,
output_tokens: value.generated,
@@ -280,15 +275,15 @@ pub(in crate::responses) fn stream_live_tools(
) {
Ok(trace) => {
if request.store != Some(false)
&& let Some(history) = &history
&& let Err(error) = store_response(
history,
&id,
&request.model,
&request.input,
&trace.response,
)
.await
&& let Some(history) = &env.store
&& let Err(error) = history
.insert(
&id,
&request.model,
&request.input,
&trace.response,
)
.await
{
failure = Some(error.to_owned());
}
+66 -55
View File
@@ -1,7 +1,11 @@
//! Unit tests of the Responses API handlers (moved out of responses.rs, STRA-338 S6).
use super::*;
use crate::{tokenizer::Tokenizer, tokenizer_assets::QWEN35_PATTERN, wire::Done};
use crate::app::ModelView;
use crate::{
adapters::ChannelEngine, responses::StreamEnv as Env, tokenizer::Tokenizer,
tokenizer_assets::QWEN35_PATTERN, wire::Done,
};
use axum::{body::to_bytes, extract::State};
use http_body_util::BodyExt;
use std::{fs, sync::Arc};
@@ -268,7 +272,7 @@ async fn console_envelope_namespaced_calls_preserve_identity_and_replay() {
assert!(replayed.contains("42\nverified"));
let (tokenizer, root) = test_tokenizer();
let (sender, source) = mpsc::channel(4096);
let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body();
let mut body = stream_live_text(request, tokenizer.clone(), source, Env::none()).into_body();
for id in tokenizer.encode(&markup, false).unwrap() {
sender.send(Ok(Event::Token(id))).await.unwrap();
}
@@ -394,7 +398,7 @@ async fn custom_live_stream_emits_plain_input_before_done_and_preserves_terminal
);
let ids = tokenizer.encode(&markup, false).unwrap();
let generated = ids.len() as u64;
let mut body = stream_live_text(request, tokenizer, source, None).into_body();
let mut body = stream_live_text(request, tokenizer, source, Env::none()).into_body();
for id in ids {
sender.send(Ok(Event::Token(id))).await.unwrap();
}
@@ -825,7 +829,10 @@ async fn input_count_requires_tokenizer_but_not_worker_or_generation_channel() {
assert_eq!(missing.status(), StatusCode::NOT_IMPLEMENTED);
let (tokenizer, root) = test_tokenizer();
let state = AppState {
tokenizer: Some(tokenizer),
model: ModelView {
tokenizer: Some(tokenizer),
..state.model
},
..state
};
let response = count_input_tokens(State(state.clone()), Ok(Json(body))).await;
@@ -834,7 +841,7 @@ async fn input_count_requires_tokenizer_but_not_worker_or_generation_channel() {
serde_json::from_slice(&to_bytes(response.into_body(), 4096).await.unwrap()).unwrap();
assert_eq!(value["object"], "response.input_tokens");
assert!(value["input_tokens"].as_u64().unwrap() > 0);
assert!(state.response_history.read().await.entries.is_empty());
assert!(state.services.responses.count().await == 0);
assert_eq!(state.lifecycle.snapshot().generation_jobs, 0);
fs::remove_dir_all(root).unwrap();
}
@@ -1065,9 +1072,9 @@ async fn endpoint_accepts_stateless_function_result_replay() {
let (tokenizer, root) = test_tokenizer();
let (commands, mut received) = mpsc::channel(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer.clone());
state.generation = Some(commands);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer.clone());
state.engine.client = Some(ChannelEngine::shared(commands));
let worker = tokio::spawn(async move {
let command = received.recv().await.unwrap();
let prompt = tokenizer.decode(&command.request.token_ids).unwrap();
@@ -1122,9 +1129,9 @@ async fn stored_response_id_replays_function_and_custom_calls_into_next_prompt()
let (tokenizer, root) = test_tokenizer();
let (commands, mut received) = mpsc::channel(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer.clone());
state.generation = Some(commands);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer.clone());
state.engine.client = Some(ChannelEngine::shared(commands));
let worker = tokio::spawn(async move {
for turn in 0..2 {
let command = received.recv().await.unwrap();
@@ -1241,7 +1248,7 @@ async fn endpoint_reports_unavailable_and_missing_adapter_truthfully() {
"worker_not_ready"
);
state.worker.write().await.state = WorkerState::Ready;
state.engine.worker.write().await.state = WorkerState::Ready;
let response = create(State(state.clone()), Ok(Json(payload))).await;
assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED);
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
@@ -1263,9 +1270,9 @@ async fn text_preview_encodes_prompt_and_returns_live_worker_tokens() {
let (tokenizer, root) = test_tokenizer();
let (sender, mut receiver) = mpsc::channel(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer);
state.generation = Some(sender);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer);
state.engine.client = Some(ChannelEngine::shared(sender));
let expected_prompt = prompt::render(
&[Message {
role: Role::User,
@@ -1277,6 +1284,7 @@ async fn text_preview_encodes_prompt_and_returns_live_worker_tokens() {
)
.unwrap();
let expected_ids = state
.model
.tokenizer
.as_ref()
.unwrap()
@@ -1324,10 +1332,10 @@ async fn text_preview_encodes_prompt_and_returns_live_worker_tokens() {
assert_eq!(response["usage"]["output_tokens"], 3);
assert!(
state
.response_history
.read()
.services
.responses
.transcript(response["id"].as_str().unwrap(), "strata-local")
.await
.get(response["id"].as_str().unwrap(), "strata-local")
.is_some()
);
worker.await.unwrap();
@@ -1347,10 +1355,10 @@ where
let (tokenizer, root) = test_tokenizer();
let (sender, mut receiver) = mpsc::channel(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer);
state.generation = Some(sender);
state.settings = Arc::new(settings);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer);
state.engine.client = Some(ChannelEngine::shared(sender));
state.services.settings = Arc::new(settings);
let worker = tokio::spawn(async move {
let command: GenerationCommand = receiver.recv().await?;
let request = command.request.clone();
@@ -1594,9 +1602,9 @@ async fn nonstreaming_tool_call_keeps_typed_arguments() {
let output_ids = tokenizer.encode(output, false).unwrap();
let (commands, mut received) = mpsc::channel(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer.clone());
state.generation = Some(commands);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer.clone());
state.engine.client = Some(ChannelEngine::shared(commands));
let worker = tokio::spawn(async move {
let command = received.recv().await.unwrap();
let prompt = tokenizer.decode(&command.request.token_ids).unwrap();
@@ -1648,9 +1656,9 @@ async fn nullable_tool_arguments_agree_across_json_and_live_sse() {
let (tokenizer, root) = test_tokenizer();
let (commands, mut received) = mpsc::channel::<GenerationCommand>(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer.clone());
state.generation = Some(commands);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer.clone());
state.engine.client = Some(ChannelEngine::shared(commands));
let output = format!(
"{}<tool_call><function=lookup><parameter=id>123</parameter><parameter=empty>null</parameter><parameter=quoted>\"123\"</parameter><parameter=days>2</parameter></function></tool_call>",
if thinking { "Think.</think>\n\n" } else { "" }
@@ -1784,9 +1792,9 @@ async fn streaming_endpoint_sends_text_before_done_and_finishes_in_order() {
let (tokenizer, root) = test_tokenizer();
let (commands, mut received) = mpsc::channel(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer);
state.generation = Some(commands);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer);
state.engine.client = Some(ChannelEngine::shared(commands));
let response = create(
State(state.clone()),
Ok(Json(json!({
@@ -1852,13 +1860,13 @@ async fn streaming_endpoint_sends_text_before_done_and_finishes_in_order() {
);
assert!(
state
.response_history
.read()
.await
.get(
.services
.responses
.transcript(
final_event["response"]["id"].as_str().unwrap(),
"strata-local"
)
.await
.is_some()
);
fs::remove_dir_all(root).unwrap();
@@ -2059,9 +2067,9 @@ async fn live_reasoning_routes_separate_content_usage_tools_and_structured_outpu
let ids = tokenizer.encode(answer, false).unwrap();
let (commands, mut received) = mpsc::channel::<GenerationCommand>(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer.clone());
state.generation = Some(commands);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer.clone());
state.engine.client = Some(ChannelEngine::shared(commands));
let worker = tokio::spawn(async move {
let command = received.recv().await.unwrap();
assert!(
@@ -2184,7 +2192,7 @@ async fn live_reasoning_routes_separate_content_usage_tools_and_structured_outpu
);
}
} else {
assert!(state.response_history.read().await.entries.is_empty());
assert!(state.services.responses.count().await == 0);
}
worker.await.unwrap();
fs::remove_dir_all(root).unwrap();
@@ -2197,7 +2205,7 @@ async fn reasoning_stream_publishes_thought_before_done_and_keeps_final_separate
let (tokenizer, root) = test_tokenizer();
let (sender, source) = mpsc::channel(128);
let request = make_request(json!({"reasoning":{"effort":"low"}}));
let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body();
let mut body = stream_live_text(request, tokenizer.clone(), source, Env::none()).into_body();
for _ in 0..4 {
body.frame().await.unwrap().unwrap();
}
@@ -2303,9 +2311,9 @@ async fn structured_live_routes_validate_text_and_preserve_tools_and_length() {
let (tokenizer, root) = test_tokenizer();
let (commands, mut received) = mpsc::channel::<GenerationCommand>(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer.clone());
state.generation = Some(commands);
state.engine.worker.write().await.state = WorkerState::Ready;
state.model.tokenizer = Some(tokenizer.clone());
state.engine.client = Some(ChannelEngine::shared(commands));
let worker = tokio::spawn(async move {
let command = received.recv().await.unwrap();
let prompt = tokenizer.decode(&command.request.token_ids).unwrap();
@@ -2397,14 +2405,14 @@ async fn structured_live_routes_validate_text_and_preserve_tools_and_length() {
}
assert!(
state
.response_history
.read()
.services
.responses
.transcript(final_response["id"].as_str().unwrap(), "strata-local")
.await
.get(final_response["id"].as_str().unwrap(), "strata-local")
.is_some()
);
} else {
assert!(state.response_history.read().await.entries.is_empty());
assert!(state.services.responses.count().await == 0);
}
worker.await.unwrap();
fs::remove_dir_all(root).unwrap();
@@ -2424,7 +2432,7 @@ async fn structured_stream_waits_for_done_before_publishing_json() {
.unwrap()
.contains("exactly one JSON object")
);
let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body();
let mut body = stream_live_text(request, tokenizer.clone(), source, Env::none()).into_body();
for _ in 0..2 {
body.frame().await.unwrap().unwrap();
}
@@ -2476,7 +2484,7 @@ async fn worker_error_terminates_stream_as_failed() {
let (tokenizer, root) = test_tokenizer();
let (engine_events, source) = mpsc::channel(2);
let request = make_request(json!({"reasoning": {"effort": "none"}}));
let mut body = stream_live_text(request, tokenizer, source, None).into_body();
let mut body = stream_live_text(request, tokenizer, source, Env::none()).into_body();
engine_events
.send(Err("mock worker failure".to_owned()))
.await
@@ -2515,7 +2523,7 @@ async fn disconnected_sse_cancels_idle_text_and_tool_sources() {
value["reasoning"] = json!({"effort":"low"});
}
let request = make_request(value);
let mut body = stream_live_text(request, tokenizer, source, None).into_body();
let mut body = stream_live_text(request, tokenizer, source, Env::none()).into_body();
// Read the initial events so the relay reaches its idle source read.
for _ in 0..if mode == 1 || mode == 2 { 2 } else { 4 } {
tokio::time::timeout(std::time::Duration::from_secs(1), body.frame())
@@ -2538,7 +2546,7 @@ async fn token_budget_terminates_live_stream_as_incomplete() {
let (tokenizer, root) = test_tokenizer();
let (engine_events, source) = mpsc::channel(2);
let request = make_request(json!({"reasoning": {"effort": "none"}}));
let mut body = stream_live_text(request, tokenizer, source, None).into_body();
let mut body = stream_live_text(request, tokenizer, source, Env::none()).into_body();
engine_events.send(Ok(Event::Token(79))).await.unwrap();
engine_events
.send(Ok(Event::Done(Done {
@@ -2581,7 +2589,7 @@ async fn live_tool_stream_emits_validated_call_before_done() {
"required":["city"],"additionalProperties":false
}}]
}));
let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body();
let mut body = stream_live_text(request, tokenizer.clone(), source, Env::none()).into_body();
let first = "Checking.\n<tool_call>\n<function=lookup>\n<parameter=city>\nOslo\n</parameter>\n</function>\n</tool_call>";
let ids = tokenizer.encode(first, false).unwrap();
for id in &ids {
@@ -2653,7 +2661,7 @@ async fn unfinished_live_tool_call_fails_without_publishing_arguments() {
"reasoning": {"effort": "none"},
"tools": [{"type":"function","name":"lookup"}]
}));
let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body();
let mut body = stream_live_text(request, tokenizer.clone(), source, Env::none()).into_body();
let ids = tokenizer
.encode("<tool_call><function=lookup><parameter=city>Os", false)
.unwrap();
@@ -2697,7 +2705,7 @@ async fn live_tool_stream_rejects_schema_violation_before_call_events() {
}}]
}));
assert!(validate_live_subset(&request).is_ok());
let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body();
let mut body = stream_live_text(request, tokenizer.clone(), source, Env::none()).into_body();
let text =
"<tool_call><function=lookup><parameter=days>wrong</parameter></function></tool_call>";
let ids = tokenizer.encode(text, false).unwrap();
@@ -2930,7 +2938,10 @@ async fn the_token_count_and_the_generation_prompt_use_the_same_encoding() {
let request: CreateRequest = serde_json::from_value(body.clone()).unwrap();
let (_, expected) = tokens_of(&tokenizer, &request);
let state = AppState {
tokenizer: Some(tokenizer.clone()),
model: ModelView {
tokenizer: Some(tokenizer.clone()),
..AppState::default().model
},
..AppState::default()
};
let response = count_input_tokens(State(state.clone()), Ok(Json(body))).await;
+10 -13
View File
@@ -30,7 +30,7 @@ pub(super) async fn expand_images(
ids: Vec<u32>,
images: &[String],
) -> Result<Prepared, Box<Response>> {
let Some(vision) = &state.vision else {
let Some(vision) = &state.model.vision else {
return Err(Box::new(api_error(
StatusCode::BAD_REQUEST,
"invalid_request_error",
@@ -65,14 +65,7 @@ pub(super) async fn expand_images(
.map_err(|e| internal(e.to_string()))?;
// Encode only while the engine is idle: the engine and the image encoder are separate processes that must
// not run on the GPU at the same time.
let encoded = {
let _turn = vision.gate.lock().await;
let mut encoded = Vec::with_capacity(images.len());
for source in images {
encoded.push(vision.encode(source).await.map_err(vision_error)?);
}
encoded
};
let encoded = vision.encode_all(images).await.map_err(vision_error)?;
let counts: Vec<usize> = encoded.iter().map(|image| image.tokens).collect();
let token_ids =
leleka_serving_policy::vision::expand_image_pads(&ids, pad, start, &literal, &counts)
@@ -103,8 +96,12 @@ pub(super) async fn prepare_input_tokens(
encode_images: bool,
) -> Result<Prepared, Box<Response>> {
if let Some(previous) = &request.previous_response_id {
let history = state.response_history.read().await;
let Some(saved) = history.get(previous, &request.model) else {
let Some(saved) = state
.services
.responses
.transcript(previous, &request.model)
.await
else {
return Err(Box::new(api_error(
StatusCode::NOT_FOUND,
"invalid_request_error",
@@ -113,7 +110,7 @@ pub(super) async fn prepare_input_tokens(
"the previous response is unavailable or belongs to a different model",
)));
};
let mut transcript = saved.to_vec();
let mut transcript = saved;
append_input(&mut transcript, &request.input);
request.input = Value::Array(transcript);
}
@@ -209,7 +206,7 @@ pub async fn count_input_tokens(
message,
);
}
let Some(tokenizer) = &state.tokenizer else {
let Some(tokenizer) = &state.model.tokenizer else {
return api_error(
StatusCode::NOT_IMPLEMENTED,
"server_error",
+284
View File
@@ -0,0 +1,284 @@
//! `strata-next serve`: the composition root. It reads the config, builds the adapters behind the gateway ports
//! (response history, MCP hub, vision encoder, engine channel, workers) and runs the HTTP server until shutdown.
use std::{path::Path, sync::Arc, time::Duration};
use tokio::sync::{mpsc, watch};
use strata_control::{BoxError, app, config::Config, tokenizer, worker};
pub async fn serve(config_path: Option<&Path>) -> Result<(), BoxError> {
let mut config = Config::load_with_path(config_path)?;
let history_dir = config.response_history_dir.clone();
let response_history = tokio::task::spawn_blocking(move || {
strata_control::responses::ResponseHistory::open(history_dir.as_deref())
})
.await??;
config.check_host().await?;
let _embedded = match config.worker.as_mut() {
Some(worker) => {
let embedded = strata_control::embedded_engine::resolve(&worker.executable)?;
if let Some(engine) = &embedded {
worker.executable = engine.executable.clone().into_os_string();
}
embedded
}
None => None,
};
config.provision().await?;
let listener = tokio::net::TcpListener::bind(config.bind).await?;
let mut settings = strata_control::settings::Settings::new(config.sampling.clone())
.with_reasoning_budget(config.reasoning_budget_tokens.clone());
if let Some(path) = config.shared_settings_file.clone() {
settings = settings.with_shared_file(path);
}
let mut state = app::AppState {
lifecycle: strata_control::lifecycle::Lifecycle::new(config.max_in_flight_requests)?,
engine: app::EngineLink {
queue_timeout: config.queue_timeout,
..Default::default()
},
http: app::HttpPolicy {
api_key: config.api_key.clone(),
cors: Arc::new(leleka_serving_policy::cors::Cors::new(
config.cors_origins.clone(),
)),
trusted_origins: Arc::new(config.trusted_origins.clone()),
},
model: app::ModelView {
name: config.model.clone(),
aliases: Arc::new(config.aliases.clone()),
..Default::default()
},
services: app::Services {
responses: strata_control::responses::HistoryResponseStore::shared(response_history),
settings: Arc::new(settings),
monitor: Arc::new(strata_control::request_monitor::RequestMonitor::new(
config.api_monitor,
)),
..Default::default()
},
};
if !config.mcp_servers.is_empty() {
let hub = Arc::new(strata_control::mcp::Hub::new(
std::mem::take(&mut config.mcp_servers),
config.mcp_settings.clone(),
));
state.services.mcp = Some(hub.clone());
// Servers start in the background (npx may download a package first); GET /mcp shows progress.
tokio::spawn(async move { hub.start().await });
}
if config.cors_origins.iter().any(|o| o == "*") && config.api_key.is_none() {
strata_control::elog!(
"CORS on /v1/*: WARNING: any web page may use the model (no API key)"
);
}
if let Some(path) = config.tokenizer_dir.as_deref() {
state.model.tokenizer = Some(Arc::new(strata_control::codec::qwen_codec(
tokenizer::Tokenizer::from_assets(path)?,
)));
state.model.chat_template = std::fs::read_to_string(path.join("chat_template.jinja"))
.ok()
.map(Arc::from);
}
if let Some(path) = config.gptoss_gguf.as_deref() {
state.model.tokenizer = Some(Arc::new(
strata_control::harmony_family::GptOssCodec::from_gguf(path)?,
));
}
// The image encoder starts before the engine: a GPU encoder takes its VRAM first, and the engine sizes its
// cache from what is left.
let mut vision_process = None;
if let Some(vision) = config.vision.take() {
strata_control::elog!("loading the vision encoder ...");
let process = strata_control::vision::Vision::start(vision).await?;
state.model.vision = Some(process.clone());
vision_process = Some(process);
}
let (shutdown_tx, shutdown_rx) = watch::channel(false);
if config.prompt_date != strata_control::responses::PromptDate::Utc {
strata_control::elog!(
"prompt date {:?} (the system message's Current date line; experimental unless a fixed date)",
config.prompt_date
);
}
strata_control::responses::set_prompt_date(config.prompt_date.clone());
if config.tool_call_recovery {
strata_control::elog!(
"tool_call_recovery is ON (experimental): a declared tool's call written in a drifted form is run as that call; see docs/api-contract.md"
);
}
strata_control::responses::set_tool_call_recovery(config.tool_call_recovery);
let runtime_task = match config.runtime.take() {
Some(runtime) => {
// The runtime backend is the Qwen path: the gpt-oss family has no runtime block (config rejects the mix).
let tokenizer = state
.model
.tokenizer
.as_ref()
.and_then(|codec| codec.qwen())
.cloned()
.ok_or("runtime requires the tokenizer assets (runtime.tokenizer_dir)")?;
let receiver = state.attach_engine(16);
let (control_sender, control_receiver) = mpsc::channel(16);
state.engine.control = Some(control_sender);
state.engine.worker.write().await.known_max_context = Some(runtime.max_context);
let backend = leleka_runtime_client::backend::GrpcBackend::new(
tokio::runtime::Handle::current(),
runtime.address,
runtime.token,
);
let worker_config = strata_control::backend_worker::BackendWorkerConfig {
tokenizer,
model: runtime.model,
runtime: runtime.runtime,
max_context: runtime.max_context,
max_output_tokens: runtime.max_output_tokens,
generation_timeout: runtime.generation_timeout,
stall_timeout: runtime.stall_timeout,
attach_retry: runtime.attach_retry,
health_interval: runtime.health_interval,
cancel_drain_timeout: Duration::from_secs(20),
prefix_view: Some(state.model.prefix_cache.clone()),
memory_view: Some(state.model.memory.clone()),
};
Some(tokio::spawn(
strata_control::backend_worker::run_backend_worker(
Box::new(backend),
worker_config,
state.engine.worker.clone(),
shutdown_rx.clone(),
receiver,
control_receiver,
),
))
}
None => None,
};
let extra_workers = std::mem::take(&mut config.extra_workers);
let mut dispatcher = None;
let worker_tasks: Vec<_> = match config.worker {
None => Vec::new(),
Some(mut main) if extra_workers.is_empty() => {
main.vision = vision_process.clone();
let receiver = state.attach_engine(16);
let (control_sender, control_receiver) = mpsc::channel(16);
state.engine.control = Some(control_sender);
vec![tokio::spawn(worker::run_supervised(
main,
state.engine.worker.clone(),
shutdown_rx,
receiver,
control_receiver,
))]
}
Some(main) => {
// several workers behind one channel (experimental): the first reports the service status and metrics.
// The pool has no administrative channel (no load/unload/control vector) and no vision: config rejects
// those combinations.
let receiver = state.attach_engine(16);
let mut members = Vec::new();
let mut tasks = Vec::new();
for (index, config) in std::iter::once(main).chain(extra_workers).enumerate() {
let status = if index == 0 {
state.engine.worker.clone()
} else {
Arc::new(tokio::sync::RwLock::new(worker::WorkerStatus::default()))
};
state.engine.pool.push(status.clone());
let (requests, received) = mpsc::channel(1);
tasks.push(tokio::spawn(worker::run_with_requests(
config,
status.clone(),
shutdown_rx.clone(),
received,
)));
members.push(strata_control::pool::Member { requests, status });
}
strata_control::elog!("{} workers in a pool", members.len());
dispatcher = Some(tokio::spawn(strata_control::pool::dispatch(
receiver, members,
)));
tasks
}
};
if let (Some(idle), true) = (config.idle_unload, state.engine.control.is_some()) {
strata_control::elog!(
"the model unloads after {} s without requests",
idle.as_secs_f64()
);
let poll = Duration::from_secs_f64(leleka_serving_policy::idle::poll_interval_s(
idle.as_secs_f64(),
));
tokio::spawn(strata_control::server_api::idle_unload_loop(
state.clone(),
idle,
poll,
));
}
strata_control::elog!("strata-control listening on {}", listener.local_addr()?);
let server_shutdown = shutdown_tx.clone();
let state_mcp = state.services.mcp.clone();
let lifecycle = state.lifecycle.clone();
let shutdown_grace = config.shutdown_grace;
// TCP_NODELAY: SSE events and small responses must not wait for the peer's delayed ACK (Nagle's algorithm).
use axum::serve::ListenerExt as _;
let listener = listener.tap_io(|tcp| {
let _ = tcp.set_nodelay(true);
});
let result = axum::serve(listener, app::router(state))
.with_graceful_shutdown(async move {
shutdown_signal().await;
lifecycle.begin_shutdown();
if !shutdown_grace.is_zero() && !lifecycle.wait_drained(shutdown_grace).await {
strata_control::elog!("Shutdown admission grace expired; stopping worker");
}
let _ = server_shutdown.send(true);
})
.await;
let _ = shutdown_tx.send(true);
if let Some(hub) = &state_mcp {
hub.close().await;
}
if let Some(vision) = &vision_process {
vision.close().await;
}
for task in worker_tasks {
task.await?;
}
if let Some(dispatcher) = dispatcher {
// its workers have stopped; requests still held by API handlers must not keep it waiting
dispatcher.abort();
}
if let Some(task) = runtime_task {
task.await?;
}
result?;
Ok(())
}
async fn shutdown_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
let mut terminate = signal(SignalKind::terminate()).expect("install SIGTERM handler");
tokio::select! {
_ = tokio::signal::ctrl_c() => {},
_ = terminate.recv() => {},
}
}
#[cfg(windows)]
{
// Ctrl-Break is how `leleka run` stops its children on Windows (they run in their own process groups).
let mut break_signal =
tokio::signal::windows::ctrl_break().expect("install Ctrl-Break handler");
tokio::select! {
result = tokio::signal::ctrl_c() => { result.expect("install Ctrl-C handler"); },
_ = break_signal.recv() => {},
}
}
#[cfg(not(any(unix, windows)))]
tokio::signal::ctrl_c()
.await
.expect("install Ctrl-C handler");
}
+24 -18
View File
@@ -44,8 +44,8 @@ pub(super) fn context_of(worker: &WorkerStatus) -> usize {
/// request's own start. `Err` is a ready-made error response.
pub async fn ensure_loaded(state: &AppState) -> Result<(), Box<Response>> {
let unloaded = {
let mut worker = state.worker.write().await;
worker.last_activity = Some(tokio::time::Instant::now());
let mut worker = state.engine.worker.write().await;
worker.last_activity = Some(state.services.clock.now());
worker.state == WorkerState::Unloaded
};
if !unloaded {
@@ -59,7 +59,7 @@ pub async fn ensure_loaded(state: &AppState) -> Result<(), Box<Response>> {
/// Ask the supervisor to load and wait until it is ready.
pub async fn load(state: &AppState) -> Result<(), LoadError> {
let Some(control) = &state.control else {
let Some(control) = &state.engine.control else {
return Err(LoadError::Failed(
"the engine cannot be loaded on demand".into(),
));
@@ -76,11 +76,11 @@ pub async fn load(state: &AppState) -> Result<(), LoadError> {
/// `POST /unload`'s core (also the idle thread): the outcome string of the Original.
pub async fn unload(state: &AppState, idle_for: Option<Duration>) -> Outcome {
let Some(control) = &state.control else {
let Some(control) = &state.engine.control else {
return Outcome::Unsupported;
};
{
let worker = state.worker.read().await;
let worker = state.engine.worker.read().await;
if is_loaded(&worker) && is_busy(state, &worker) {
return Outcome::Busy;
}
@@ -118,7 +118,12 @@ pub(super) fn api_server_error(message: &str) -> Response {
pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) {
loop {
tokio::time::sleep(poll).await;
if state.control.as_ref().is_none_or(mpsc::Sender::is_closed) {
if state
.engine
.control
.as_ref()
.is_none_or(mpsc::Sender::is_closed)
{
return;
}
let outcome = unload(&state, Some(idle)).await;
@@ -135,11 +140,11 @@ pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) {
/// `GET /api/health` (the Python server's `/health`): who answers and whether the engine is loaded.
pub async fn api_health(State(state): State<AppState>) -> Response {
let worker = *state.worker.read().await;
let worker = *state.engine.worker.read().await;
reply(
StatusCode::OK,
json!({"status": "ok", "max_context": context_of(&worker), "model": state.model,
"images": state.vision.is_some(), "api_key": state.api_key.is_some(),
json!({"status": "ok", "max_context": context_of(&worker), "model": state.model.name,
"images": state.model.vision.is_some(), "api_key": state.http.api_key.is_some(),
"loaded": is_loaded(&worker), "service": "strata"}),
)
}
@@ -147,9 +152,10 @@ pub async fn api_health(State(state): State<AppState>) -> Response {
pub(super) fn model_names(state: &AppState) -> Vec<String> {
state
.model
.name
.iter()
.cloned()
.chain(state.aliases.iter().cloned())
.chain(state.model.aliases.iter().cloned())
.collect()
}
@@ -191,20 +197,20 @@ pub(super) fn percent_decode(text: &str) -> String {
/// what this server can do.
pub async fn props(State(state): State<AppState>, request: Request) -> Response {
let asked = query_param(request.uri().query(), "model")
.or_else(|| state.model.clone())
.or_else(|| state.model.name.clone())
.unwrap_or_default();
if !model_names(&state).contains(&asked) {
return reply(StatusCode::NOT_FOUND, error_body(None, "model not found"));
}
let worker = *state.worker.read().await;
let worker = *state.engine.worker.read().await;
if !is_loaded(&worker) && worker.state != WorkerState::Unloaded {
return reply(
StatusCode::SERVICE_UNAVAILABLE,
error_body(None, "the engine is not running"),
);
}
let merged = state.settings.merged();
let shared = state.settings.shared();
let merged = state.services.settings.merged();
let shared = state.services.settings.shared();
reply(
StatusCode::OK,
json!({
@@ -213,10 +219,10 @@ pub async fn props(State(state): State<AppState>, request: Request) -> Response
"params": merged.props_params(&shared),
},
"total_slots": 1,
"model_alias": state.model,
"chat_template": state.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE),
"modalities": {"vision": state.vision.is_some()},
"models_autoload": state.control.is_some(),
"model_alias": state.model.name,
"chat_template": state.model.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE),
"modalities": {"vision": state.model.vision.is_some()},
"models_autoload": state.engine.control.is_some(),
"is_sleeping": !is_loaded(&worker),
"build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")),
}),
+10 -10
View File
@@ -28,13 +28,13 @@ pub async fn v1_load(State(state): State<AppState>, headers: HeaderMap, body: By
return *response;
}
{
let worker = state.worker.read().await;
let worker = state.engine.worker.read().await;
if is_busy(&state, &worker) {
return model_busy();
}
}
state.worker.write().await.last_activity = Some(tokio::time::Instant::now());
if state.worker.read().await.state != WorkerState::Ready
state.engine.worker.write().await.last_activity = Some(state.services.clock.now());
if state.engine.worker.read().await.state != WorkerState::Ready
&& let Err(error) = load(&state).await
{
return load_error_response(&error);
@@ -77,7 +77,7 @@ pub async fn v1_reconfigure(
),
);
}
let Some(control) = &state.control else {
let Some(control) = &state.engine.control else {
return reply(
StatusCode::NOT_IMPLEMENTED,
error_body(None, "this server has no engine to reconfigure"),
@@ -119,7 +119,7 @@ pub async fn v1_reconfigure(
/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). Without
/// `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or 404 once evicted.
pub async fn api_requests(State(state): State<AppState>, RawQuery(query): RawQuery) -> Response {
if !state.monitor.enabled() {
if !state.services.monitor.enabled() {
return not_found().await;
}
let id = query.as_deref().and_then(|query| {
@@ -128,7 +128,7 @@ pub async fn api_requests(State(state): State<AppState>, RawQuery(query): RawQue
.find_map(|pair| pair.strip_prefix("id=").map(|id| id.to_owned()))
});
if let Some(id) = id {
return match state.monitor.detail(&id) {
return match state.services.monitor.detail(&id) {
Some(record) => reply(StatusCode::OK, record),
None => reply(
StatusCode::NOT_FOUND,
@@ -136,11 +136,11 @@ pub async fn api_requests(State(state): State<AppState>, RawQuery(query): RawQue
),
};
}
let worker = *state.worker.read().await;
let worker = *state.engine.worker.read().await;
reply(
StatusCode::OK,
json!({"requests": state.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false,
"loaded": is_loaded(&worker), "auto_load": state.control.is_some()}),
json!({"requests": state.services.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false,
"loaded": is_loaded(&worker), "auto_load": state.engine.control.is_some()}),
)
}
@@ -185,7 +185,7 @@ pub async fn cors_layer(State(cors): State<Arc<Cors>>, request: Request, next: N
/// `GET /mcp`: the configured MCP servers, their state and tools (empty when there are none).
pub async fn mcp_status(State(state): State<AppState>) -> Response {
let body = match &state.mcp {
let body = match &state.services.mcp {
Some(hub) => hub.status().await,
None => json!({"servers": [], "tools": 0}),
};
+17 -15
View File
@@ -5,7 +5,7 @@ use super::*;
/// `GET /slots`: one slot while the engine is loaded, none otherwise.
pub async fn slots(State(state): State<AppState>) -> Response {
let worker = *state.worker.read().await;
let worker = *state.engine.worker.read().await;
if !is_loaded(&worker) {
return reply(StatusCode::OK, json!([]));
}
@@ -37,6 +37,7 @@ pub async fn v1_prefix_match(State(state): State<AppState>, body: Bytes) -> Resp
);
};
match state
.model
.prefix_cache
.prefix_match(request["namespace"].as_str(), &hashes)
{
@@ -54,7 +55,7 @@ pub async fn v1_status(State(state): State<AppState>) -> Response {
}
pub(super) async fn status_value(state: &AppState) -> Value {
let worker = *state.worker.read().await;
let worker = *state.engine.worker.read().await;
let lifecycle = state.lifecycle.snapshot();
let busy = worker.metrics.active_since.is_some();
let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy));
@@ -63,6 +64,7 @@ pub(super) async fn status_value(state: &AppState) -> Value {
.last_activity
.map(|at| now_s().saturating_sub(at.elapsed().as_secs()));
let started = state
.services
.started_at
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
@@ -83,26 +85,26 @@ pub(super) async fn status_value(state: &AppState) -> Value {
value
});
let mut body = json!({
"service": "strata", "model": state.model,
"loaded": is_loaded(&worker), "auto_load": state.control.is_some(),
"service": "strata", "model": state.model.name,
"loaded": is_loaded(&worker), "auto_load": state.engine.control.is_some(),
"structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate",
"constrained_decoding": false, "stream_buffered": true},
"engine": env!("CARGO_PKG_VERSION"),
"started": started,
"uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()),
"uptime_s": crate::app::uptime_s(state),
"cache_max_tokens": context,
"context": {"native": context, "max_positions": context},
"concurrency": {"serving": 1, "requested": 1},
"dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"],
"vision": {"enabled": state.vision.is_some(), "available": state.vision.is_some(), "error": null},
"vision": {"enabled": state.model.vision.is_some(), "available": state.model.vision.is_some(), "error": null},
"activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued,
"last_request_at": last_at},
"last_timings": timings,
"machine": machine_view(&state.memory),
"memory": state.memory.status(),
"machine": machine_view(&state.model.memory),
"memory": state.model.memory.status(),
});
// Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface).
let prefix = json!(state.prefix_cache.status());
let prefix = json!(state.model.prefix_cache.status());
if !prefix.is_null() {
body["prefix_cache"] = prefix;
}
@@ -111,7 +113,7 @@ pub(super) async fn status_value(state: &AppState) -> Value {
/// `GET /settings`.
pub async fn settings_get(State(state): State<AppState>) -> Response {
let shared = state.settings.shared();
let shared = state.services.settings.shared();
reply(
StatusCode::OK,
json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}),
@@ -128,7 +130,7 @@ pub(super) fn own_page_check(
header_str(headers, "content-type"),
header_str(headers, "origin"),
header_str(headers, "host"),
&state.trusted_origins,
&state.http.trusted_origins,
)
.map_err(|e| {
Box::new(reply(
@@ -162,7 +164,7 @@ pub async fn settings_post(
}
};
let defaults = value.get("defaults").cloned().unwrap_or(Value::Null);
match state.settings.set_shared(&defaults) {
match state.services.settings.set_shared(&defaults) {
Ok(shared) => {
if shared.is_empty() {
crate::elog!("other apps use their own settings again");
@@ -196,8 +198,8 @@ pub async fn unload_post(State(state): State<AppState>) -> Response {
/// `POST /load`: load now, e.g. ahead of a request.
pub async fn load_post(State(state): State<AppState>) -> Response {
state.worker.write().await.last_activity = Some(tokio::time::Instant::now());
if state.worker.read().await.state == WorkerState::Ready {
state.engine.worker.write().await.last_activity = Some(state.services.clock.now());
if state.engine.worker.read().await.state == WorkerState::Ready {
return reply(StatusCode::OK, json!({"status": "loaded"}));
}
match load(&state).await {
@@ -232,7 +234,7 @@ pub(super) fn model_control_prelude(
own_page_check(state, headers, "the model can be loaded or unloaded")?;
match object.get("model") {
None | Some(Value::Null) => {}
Some(Value::String(name)) if state.model.as_deref() == Some(name.as_str()) => {}
Some(Value::String(name)) if state.model.name.as_deref() == Some(name.as_str()) => {}
Some(_) => {
return Err(Box::new(reply(
StatusCode::NOT_FOUND,
+1 -407
View File
@@ -17,413 +17,7 @@ struct Options {
const CONTROL_USAGE: &str = "usage: strata-next service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]";
#[cfg(unix)]
mod unix {
use super::*;
use std::{
fs::{self, OpenOptions},
io::{Read, Write},
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
process::Stdio,
time::Duration,
};
pub(super) fn publish(directory: &Path, name: &str, content: &[u8]) -> Result<bool, String> {
validate_name(name)?;
let mut builder = fs::DirBuilder::new();
builder.recursive(true).mode(0o700);
builder
.create(directory)
.map_err(|e| format!("create user unit directory: {e}"))?;
check_directory(directory)?;
let path = directory.join(name);
match same_file(&path, content) {
Ok(()) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
Err(e) => return Err(format!("refusing existing unit {}: {e}", path.display())),
}
let temp = directory.join(format!(
".strata-unit-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| e.to_string())?
.as_nanos()
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&temp)
.map_err(|e| e.to_string())?;
let result = (|| {
file.write_all(content)?;
file.sync_all()?;
let created = match fs::hard_link(&temp, &path) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
same_file(&path, content)?;
false
}
Err(e) => return Err(e),
};
fs::File::open(directory)?.sync_all()?;
Ok(created)
})();
let cleanup = fs::remove_file(&temp);
result
.map_err(|e: std::io::Error| format!("publish unit: {e}"))
.and_then(|created| {
cleanup.map_err(|e| format!("remove unit staging file: {e}"))?;
Ok(created)
})
}
pub(super) fn check_directory(directory: &Path) -> Result<(), String> {
let metadata = fs::symlink_metadata(directory).map_err(|e| e.to_string())?;
if !metadata.is_dir()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o022 != 0
{
return Err(
"user unit directory must be an owned directory, not writable by other users"
.into(),
);
}
Ok(())
}
pub(super) fn same_file(path: &Path, content: &[u8]) -> std::io::Result<()> {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)?;
let metadata = file.metadata()?;
if !metadata.is_file()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o077 != 0
|| metadata.len() != content.len() as u64
{
return Err(std::io::Error::other(
"requires an owned private regular file with identical content",
));
}
let mut actual = Vec::new();
(&mut file)
.take(content.len() as u64 + 1)
.read_to_end(&mut actual)?;
if actual != content {
return Err(std::io::Error::other(
"different unit content; choose a new unit name",
));
}
Ok(())
}
// Never replace/remove a conflicting activation link even for a valid unit.
pub(super) fn check_activation_link(path: &Path) -> Result<(), String> {
let directory = path
.parent()
.ok_or("unit parent absent")?
.join("default.target.wants");
match fs::symlink_metadata(&directory) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Ok(meta) if meta.is_dir() && meta.uid() == unsafe { libc::geteuid() }
&& meta.mode() & 0o022 == 0 => (),
_ => return Err("activation directory must be an owned real directory without group/other write access".into()),
}
let link = directory.join(path.file_name().ok_or("unit name absent")?);
match fs::symlink_metadata(&link) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Ok(meta)
if meta.file_type().is_symlink()
&& link.canonicalize().ok()
== Some(path.canonicalize().map_err(|e| e.to_string())?) =>
{
Ok(())
}
_ => Err(
"conflicting activation link; reconcile it explicitly before enable/disable".into(),
),
}
}
// The manager may have different XDG paths or higher-priority runtime units.
// Refuse to start a different service or a unit modified by existing drop-ins.
pub(super) async fn verify_loaded_unit(unit: &str, path: &Path) -> Result<(), String> {
let output = show(unit, &["FragmentPath", "DropInPaths", "NeedDaemonReload"]).await?;
let fragment = output
.lines()
.find_map(|s| s.strip_prefix("FragmentPath="))
.ok_or("manager has no unit fragment")?;
let drop_ins = output
.lines()
.find_map(|s| s.strip_prefix("DropInPaths="))
.ok_or("manager did not report drop-ins")?;
let reload = output
.lines()
.find_map(|s| s.strip_prefix("NeedDaemonReload="));
if reload != Some("no") {
return Err("systemd unit is stale or reload state is unknown; reconcile the unit and run daemon-reload explicitly before control".into());
}
if !drop_ins.is_empty()
|| Path::new(fragment).canonicalize().ok()
!= Some(path.canonicalize().map_err(|e| e.to_string())?)
{
return Err("systemd resolves a different unit or existing drop-ins; use the manager's config directory and a new unit name".into());
}
Ok(())
}
async fn show(unit: &str, properties: &[&str]) -> Result<String, String> {
use tokio::io::AsyncReadExt;
let mut child = tokio::process::Command::new("systemctl")
.args(["--user", "--no-pager", "show"])
.args(properties.iter().map(|p| format!("--property={p}")))
.args(["--", unit])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("verify loaded unit: {e}"))?;
let mut stdout = child
.stdout
.take()
.ok_or("missing systemctl output pipe")?
.take(16385);
let mut bytes = Vec::new();
let result = tokio::time::timeout(Duration::from_secs(30), async {
stdout.read_to_end(&mut bytes).await?;
if bytes.len() > 16384 {
return Err(std::io::Error::other("systemctl output exceeded limit"));
}
let status = child.wait().await?;
if !status.success() {
return Err(std::io::Error::other("systemctl show failed"));
}
Ok(())
})
.await;
if !matches!(result, Ok(Ok(()))) {
let _ = child.kill().await;
return Err(format!("verify loaded unit failed: {result:?}"));
}
String::from_utf8(bytes).map_err(|_| "invalid systemctl output".into())
}
pub(super) async fn status(unit: &str) -> Result<serde_json::Value, String> {
parse_status(
&show(
unit,
&["ActiveState", "SubState", "MainPID", "UnitFileState"],
)
.await?,
)
}
fn parse_status(output: &str) -> Result<serde_json::Value, String> {
let mut values = std::collections::BTreeMap::new();
for line in output.lines() {
let (key, value) = line.split_once('=').ok_or("malformed manager status")?;
if !matches!(
key,
"ActiveState" | "SubState" | "MainPID" | "UnitFileState"
) || values.insert(key, value).is_some()
{
return Err("unexpected or duplicate manager status property".into());
}
}
let state = |key| -> Result<&str, String> {
let value = *values.get(key).ok_or("incomplete manager status")?;
if value.is_empty()
|| value.len() > 64
|| !value
.bytes()
.all(|b| b.is_ascii_lowercase() || b"-_".contains(&b))
{
return Err("invalid manager state".into());
}
Ok(value)
};
let pid = *values.get("MainPID").ok_or("manager PID absent")?;
if pid.is_empty() || !pid.bytes().all(|b| b.is_ascii_digit()) {
return Err("invalid manager PID".into());
}
let pid = pid.parse::<u32>().map_err(|_| "invalid manager PID")?;
Ok(
serde_json::json!({"active_state":state("ActiveState")?,"sub_state":state("SubState")?,"main_pid":pid,"unit_file_state":state("UnitFileState")?}),
)
}
pub(super) async fn systemctl(
action: &str,
unit: &str,
timeout: Duration,
) -> Result<(), String> {
let mut command = tokio::process::Command::new("systemctl");
command.args(["--user", "--no-pager", action]);
match action {
"daemon-reload" => (),
"start" | "stop" | "restart" | "enable" | "disable" => {
command.args(["--", unit]);
}
_ => return Err("unsupported systemctl action".into()),
}
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
bounded(&mut command, timeout)
.await
.map_err(|e| format!("systemctl --user {action}: {e}"))
}
async fn bounded(
command: &mut tokio::process::Command,
timeout: Duration,
) -> Result<(), String> {
let mut child = command.spawn().map_err(|e| e.to_string())?;
match tokio::time::timeout(timeout, child.wait()).await {
Ok(Ok(status)) if status.success() => Ok(()),
Ok(result) => Err(format!("command failed: {result:?}")),
Err(_) => {
child
.kill()
.await
.map_err(|e| format!("timed out; kill/reap failed: {e}"))?;
Err("timed out; client killed and reaped (manager job may still be pending)".into())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::{PermissionsExt, symlink};
#[test]
fn atomic_reuse_and_conflicts_preserve_bytes() {
let root = std::env::temp_dir().join(format!(
"strata-unit-test-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-test.service";
assert!(publish(&root, name, b"one").unwrap());
let path = root.join(name);
let inode = fs::metadata(&path).unwrap().ino();
assert!(!publish(&root, name, b"one").unwrap());
assert!(publish(&root, name, b"two").is_err());
assert_eq!(fs::read(&path).unwrap(), b"one");
assert_eq!(fs::metadata(&path).unwrap().ino(), inode);
assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, 0o600);
fs::remove_file(&path).unwrap();
symlink(root.join("missing"), &path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_dir(&path).unwrap();
assert!(publish(&root, name, b"one").unwrap());
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
assert!(publish(&root, name, b"one").is_err());
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn manager_status_is_limited_and_strict() {
let good =
"ActiveState=active\nSubState=running\nMainPID=123\nUnitFileState=disabled\n";
let value = parse_status(good).unwrap();
assert_eq!(value["main_pid"], 123);
assert_eq!(value["active_state"], "active");
assert_eq!(value["unit_file_state"], "disabled");
assert_eq!(
parse_status(
"MainPID=0\nSubState=dead\nActiveState=inactive\nUnitFileState=enabled\n"
)
.unwrap()["main_pid"],
0
);
for bad in [
"",
"MainPID=1\n",
"ActiveState=active\nSubState=running\nMainPID=-1\n",
"ActiveState=active\nSubState=running\nMainPID=4294967296\n",
"ActiveState=active\nSubState=running\nMainPID=+1\n",
"ActiveState=active\nSubState=secret text\nMainPID=1\n",
] {
assert!(parse_status(bad).is_err());
}
assert!(parse_status(&format!("{good}MainPID=2\n")).is_err());
assert!(parse_status(&format!("{good}Environment=secret\n")).is_err());
assert!(parse_status(&good.replace("disabled", "")).is_err());
assert!(parse_status(&format!("{good}UnitFileState=enabled\n")).is_err());
}
#[test]
fn activation_link_conflicts_are_preserved() {
let root = std::env::temp_dir().join(format!(
"strata-activation-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-activation.service";
publish(&root, name, b"owned unit").unwrap();
let path = root.join(name);
assert!(check_activation_link(&path).is_ok());
let wants = root.join("default.target.wants");
fs::create_dir(&wants).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o755)).unwrap();
let link = wants.join(name);
symlink(Path::new("..").join(name), &link).unwrap();
assert!(check_activation_link(&path).is_ok());
fs::remove_file(&link).unwrap();
symlink(root.join("foreign"), &link).unwrap();
let inode = fs::symlink_metadata(&link).unwrap().ino();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::symlink_metadata(&link).unwrap().ino(), inode);
fs::remove_file(&link).unwrap();
fs::write(&link, "foreign bytes").unwrap();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::read(&link).unwrap(), b"foreign bytes");
fs::remove_file(&link).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o777)).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_dir(&wants).unwrap();
symlink(&root, &wants).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_file(&wants).unwrap();
fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn failed_and_timed_out_clients_are_reported_and_reaped() {
assert!(
bounded(
tokio::process::Command::new("false").kill_on_drop(true),
Duration::from_secs(1)
)
.await
.is_err()
);
let mut command = tokio::process::Command::new("sleep");
command.arg("30").kill_on_drop(true);
let start = std::time::Instant::now();
let error = bounded(&mut command, Duration::from_millis(20))
.await
.unwrap_err();
assert!(error.contains("killed and reaped"));
assert!(start.elapsed() < Duration::from_secs(2));
}
}
}
mod unix;
#[cfg(test)]
mod tests;
+280
View File
@@ -0,0 +1,280 @@
//! Unix side of the unit installer: private publication of the unit file and the `systemctl --user` calls.
use super::*;
use std::{
fs::{self, OpenOptions},
io::{Read, Write},
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
process::Stdio,
time::Duration,
};
pub(super) fn publish(directory: &Path, name: &str, content: &[u8]) -> Result<bool, String> {
validate_name(name)?;
let mut builder = fs::DirBuilder::new();
builder.recursive(true).mode(0o700);
builder
.create(directory)
.map_err(|e| format!("create user unit directory: {e}"))?;
check_directory(directory)?;
let path = directory.join(name);
match same_file(&path, content) {
Ok(()) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
Err(e) => return Err(format!("refusing existing unit {}: {e}", path.display())),
}
let temp = directory.join(format!(
".strata-unit-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| e.to_string())?
.as_nanos()
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&temp)
.map_err(|e| e.to_string())?;
let result = (|| {
file.write_all(content)?;
file.sync_all()?;
let created = match fs::hard_link(&temp, &path) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
same_file(&path, content)?;
false
}
Err(e) => return Err(e),
};
fs::File::open(directory)?.sync_all()?;
Ok(created)
})();
let cleanup = fs::remove_file(&temp);
result
.map_err(|e: std::io::Error| format!("publish unit: {e}"))
.and_then(|created| {
cleanup.map_err(|e| format!("remove unit staging file: {e}"))?;
Ok(created)
})
}
pub(super) fn check_directory(directory: &Path) -> Result<(), String> {
let metadata = fs::symlink_metadata(directory).map_err(|e| e.to_string())?;
if !metadata.is_dir()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o022 != 0
{
return Err(
"user unit directory must be an owned directory, not writable by other users".into(),
);
}
Ok(())
}
pub(super) fn same_file(path: &Path, content: &[u8]) -> std::io::Result<()> {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)?;
let metadata = file.metadata()?;
if !metadata.is_file()
|| metadata.uid() != unsafe { libc::geteuid() }
|| metadata.mode() & 0o077 != 0
|| metadata.len() != content.len() as u64
{
return Err(std::io::Error::other(
"requires an owned private regular file with identical content",
));
}
let mut actual = Vec::new();
(&mut file)
.take(content.len() as u64 + 1)
.read_to_end(&mut actual)?;
if actual != content {
return Err(std::io::Error::other(
"different unit content; choose a new unit name",
));
}
Ok(())
}
// Never replace/remove a conflicting activation link even for a valid unit.
pub(super) fn check_activation_link(path: &Path) -> Result<(), String> {
let directory = path
.parent()
.ok_or("unit parent absent")?
.join("default.target.wants");
match fs::symlink_metadata(&directory) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Ok(meta)
if meta.is_dir()
&& meta.uid() == unsafe { libc::geteuid() }
&& meta.mode() & 0o022 == 0 => {}
_ => return Err(
"activation directory must be an owned real directory without group/other write access"
.into(),
),
}
let link = directory.join(path.file_name().ok_or("unit name absent")?);
match fs::symlink_metadata(&link) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Ok(meta)
if meta.file_type().is_symlink()
&& link.canonicalize().ok()
== Some(path.canonicalize().map_err(|e| e.to_string())?) =>
{
Ok(())
}
_ => {
Err("conflicting activation link; reconcile it explicitly before enable/disable".into())
}
}
}
// The manager may have different XDG paths or higher-priority runtime units.
// Refuse to start a different service or a unit modified by existing drop-ins.
pub(super) async fn verify_loaded_unit(unit: &str, path: &Path) -> Result<(), String> {
let output = show(unit, &["FragmentPath", "DropInPaths", "NeedDaemonReload"]).await?;
let fragment = output
.lines()
.find_map(|s| s.strip_prefix("FragmentPath="))
.ok_or("manager has no unit fragment")?;
let drop_ins = output
.lines()
.find_map(|s| s.strip_prefix("DropInPaths="))
.ok_or("manager did not report drop-ins")?;
let reload = output
.lines()
.find_map(|s| s.strip_prefix("NeedDaemonReload="));
if reload != Some("no") {
return Err("systemd unit is stale or reload state is unknown; reconcile the unit and run daemon-reload explicitly before control".into());
}
if !drop_ins.is_empty()
|| Path::new(fragment).canonicalize().ok()
!= Some(path.canonicalize().map_err(|e| e.to_string())?)
{
return Err("systemd resolves a different unit or existing drop-ins; use the manager's config directory and a new unit name".into());
}
Ok(())
}
async fn show(unit: &str, properties: &[&str]) -> Result<String, String> {
use tokio::io::AsyncReadExt;
let mut child = tokio::process::Command::new("systemctl")
.args(["--user", "--no-pager", "show"])
.args(properties.iter().map(|p| format!("--property={p}")))
.args(["--", unit])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("verify loaded unit: {e}"))?;
let mut stdout = child
.stdout
.take()
.ok_or("missing systemctl output pipe")?
.take(16385);
let mut bytes = Vec::new();
let result = tokio::time::timeout(Duration::from_secs(30), async {
stdout.read_to_end(&mut bytes).await?;
if bytes.len() > 16384 {
return Err(std::io::Error::other("systemctl output exceeded limit"));
}
let status = child.wait().await?;
if !status.success() {
return Err(std::io::Error::other("systemctl show failed"));
}
Ok(())
})
.await;
if !matches!(result, Ok(Ok(()))) {
let _ = child.kill().await;
return Err(format!("verify loaded unit failed: {result:?}"));
}
String::from_utf8(bytes).map_err(|_| "invalid systemctl output".into())
}
pub(super) async fn status(unit: &str) -> Result<serde_json::Value, String> {
parse_status(
&show(
unit,
&["ActiveState", "SubState", "MainPID", "UnitFileState"],
)
.await?,
)
}
fn parse_status(output: &str) -> Result<serde_json::Value, String> {
let mut values = std::collections::BTreeMap::new();
for line in output.lines() {
let (key, value) = line.split_once('=').ok_or("malformed manager status")?;
if !matches!(
key,
"ActiveState" | "SubState" | "MainPID" | "UnitFileState"
) || values.insert(key, value).is_some()
{
return Err("unexpected or duplicate manager status property".into());
}
}
let state = |key| -> Result<&str, String> {
let value = *values.get(key).ok_or("incomplete manager status")?;
if value.is_empty()
|| value.len() > 64
|| !value
.bytes()
.all(|b| b.is_ascii_lowercase() || b"-_".contains(&b))
{
return Err("invalid manager state".into());
}
Ok(value)
};
let pid = *values.get("MainPID").ok_or("manager PID absent")?;
if pid.is_empty() || !pid.bytes().all(|b| b.is_ascii_digit()) {
return Err("invalid manager PID".into());
}
let pid = pid.parse::<u32>().map_err(|_| "invalid manager PID")?;
Ok(
serde_json::json!({"active_state":state("ActiveState")?,"sub_state":state("SubState")?,"main_pid":pid,"unit_file_state":state("UnitFileState")?}),
)
}
pub(super) async fn systemctl(action: &str, unit: &str, timeout: Duration) -> Result<(), String> {
let mut command = tokio::process::Command::new("systemctl");
command.args(["--user", "--no-pager", action]);
match action {
"daemon-reload" => (),
"start" | "stop" | "restart" | "enable" | "disable" => {
command.args(["--", unit]);
}
_ => return Err("unsupported systemctl action".into()),
}
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true);
bounded(&mut command, timeout)
.await
.map_err(|e| format!("systemctl --user {action}: {e}"))
}
async fn bounded(command: &mut tokio::process::Command, timeout: Duration) -> Result<(), String> {
let mut child = command.spawn().map_err(|e| e.to_string())?;
match tokio::time::timeout(timeout, child.wait()).await {
Ok(Ok(status)) if status.success() => Ok(()),
Ok(result) => Err(format!("command failed: {result:?}")),
Err(_) => {
child
.kill()
.await
.map_err(|e| format!("timed out; kill/reap failed: {e}"))?;
Err("timed out; client killed and reaped (manager job may still be pending)".into())
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,122 @@
//! Tests of the unit publication and the `systemctl` wrapper (moved out of service_install.rs, STRA-338 S7).
use super::*;
use std::os::unix::fs::{PermissionsExt, symlink};
#[test]
fn atomic_reuse_and_conflicts_preserve_bytes() {
let root = std::env::temp_dir().join(format!(
"strata-unit-test-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-test.service";
assert!(publish(&root, name, b"one").unwrap());
let path = root.join(name);
let inode = fs::metadata(&path).unwrap().ino();
assert!(!publish(&root, name, b"one").unwrap());
assert!(publish(&root, name, b"two").is_err());
assert_eq!(fs::read(&path).unwrap(), b"one");
assert_eq!(fs::metadata(&path).unwrap().ino(), inode);
assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, 0o600);
fs::remove_file(&path).unwrap();
symlink(root.join("missing"), &path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
assert!(publish(&root, name, b"one").is_err());
fs::remove_dir(&path).unwrap();
assert!(publish(&root, name, b"one").unwrap());
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
assert!(publish(&root, name, b"one").is_err());
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn manager_status_is_limited_and_strict() {
let good = "ActiveState=active\nSubState=running\nMainPID=123\nUnitFileState=disabled\n";
let value = parse_status(good).unwrap();
assert_eq!(value["main_pid"], 123);
assert_eq!(value["active_state"], "active");
assert_eq!(value["unit_file_state"], "disabled");
assert_eq!(
parse_status("MainPID=0\nSubState=dead\nActiveState=inactive\nUnitFileState=enabled\n")
.unwrap()["main_pid"],
0
);
for bad in [
"",
"MainPID=1\n",
"ActiveState=active\nSubState=running\nMainPID=-1\n",
"ActiveState=active\nSubState=running\nMainPID=4294967296\n",
"ActiveState=active\nSubState=running\nMainPID=+1\n",
"ActiveState=active\nSubState=secret text\nMainPID=1\n",
] {
assert!(parse_status(bad).is_err());
}
assert!(parse_status(&format!("{good}MainPID=2\n")).is_err());
assert!(parse_status(&format!("{good}Environment=secret\n")).is_err());
assert!(parse_status(&good.replace("disabled", "")).is_err());
assert!(parse_status(&format!("{good}UnitFileState=enabled\n")).is_err());
}
#[test]
fn activation_link_conflicts_are_preserved() {
let root = std::env::temp_dir().join(format!(
"strata-activation-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let name = "strata-next-activation.service";
publish(&root, name, b"owned unit").unwrap();
let path = root.join(name);
assert!(check_activation_link(&path).is_ok());
let wants = root.join("default.target.wants");
fs::create_dir(&wants).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o755)).unwrap();
let link = wants.join(name);
symlink(Path::new("..").join(name), &link).unwrap();
assert!(check_activation_link(&path).is_ok());
fs::remove_file(&link).unwrap();
symlink(root.join("foreign"), &link).unwrap();
let inode = fs::symlink_metadata(&link).unwrap().ino();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::symlink_metadata(&link).unwrap().ino(), inode);
fs::remove_file(&link).unwrap();
fs::write(&link, "foreign bytes").unwrap();
assert!(check_activation_link(&path).is_err());
assert_eq!(fs::read(&link).unwrap(), b"foreign bytes");
fs::remove_file(&link).unwrap();
fs::set_permissions(&wants, fs::Permissions::from_mode(0o777)).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_dir(&wants).unwrap();
symlink(&root, &wants).unwrap();
assert!(check_activation_link(&path).is_err());
fs::remove_file(&wants).unwrap();
fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn failed_and_timed_out_clients_are_reported_and_reaped() {
assert!(
bounded(
tokio::process::Command::new("false").kill_on_drop(true),
Duration::from_secs(1)
)
.await
.is_err()
);
let mut command = tokio::process::Command::new("sleep");
command.arg("30").kill_on_drop(true);
let start = std::time::Instant::now();
let error = bounded(&mut command, Duration::from_millis(20))
.await
.unwrap_err();
assert!(error.contains("killed and reaped"));
assert!(start.elapsed() < Duration::from_secs(2));
}
+1 -2
View File
@@ -2,7 +2,6 @@
use std::{
collections::BTreeMap,
error::Error,
fs::{self, File},
io::Write,
path::{Path, PathBuf},
@@ -12,7 +11,7 @@ use serde_json::json;
use crate::gguf;
type Result<T> = std::result::Result<T, Box<dyn Error>>;
type Result<T> = std::result::Result<T, crate::BoxError>;
pub(crate) use leleka_tokenizer::QWEN35_PATTERN;

Some files were not shown because too many files have changed in this diff Show More