feat(control-plane): runtime block selects the runtime backend; strata-next serves in front of leleka-inference

runtime.{address,token_env,tokenizer_dir,model,mode,max_context} are validated at load
(loopback only, credential from the environment and never printed, exclusive with
engine/native_model/mtp_pack/vision/gpu). serve spawns backend_worker over GrpcBackend.
The worker carries the runtime's output-token cap in WorkerStatus; a default budget never
exceeds it, an explicit request above it is refused. Request ids are UUIDs, as the
runtime contract requires.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-16 02:46:22 +02:00
co-authored by Claude Sonnet 5.5
parent c9aad38caa
commit c8601d0b2c
10 changed files with 419 additions and 28 deletions
Generated
+2
View File
@@ -2145,6 +2145,7 @@ dependencies = [
"leleka-model-format",
"leleka-offline-tools",
"leleka-quant-core",
"leleka-runtime-client",
"leleka-sampler-ref",
"leleka-serving-policy",
"leleka-tokenizer",
@@ -2159,6 +2160,7 @@ dependencies = [
"sha2",
"subtle",
"tokio",
"uuid",
"webpki-root-certs",
]
+2
View File
@@ -14,6 +14,7 @@ axum = "0.8"
futures-core = "0.3"
hex = "0.4"
leleka-backend-api = { path = "../crates/backend-api" }
leleka-runtime-client = { path = "../crates/runtime-client" }
leleka-tokenizer = { path = "../crates/tokenizer" }
leleka-sampler-ref = { path = "../crates/sampler-ref" }
leleka-serving-policy = { path = "../crates/serving-policy" }
@@ -33,6 +34,7 @@ serde_json = { version = "1", features = ["float_roundtrip"] }
sha2 = "0.11"
subtle = "2.6.1"
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] }
uuid = { version = "1", features = ["v4"] }
webpki-root-certs = "1.0"
[build-dependencies]
+13 -13
View File
@@ -26,10 +26,7 @@
//! gRPC backend never issues a load RPC), so an HTTP request can never start a multi-gigabyte load.
use std::{
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
sync::{Arc, Mutex},
time::Duration,
};
@@ -59,6 +56,9 @@ pub struct BackendWorkerConfig {
pub runtime: api::RuntimeConfig,
/// The engine's context in tokens (`n + max_new + 8 <= max_context` is checked before a request).
pub max_context: usize,
/// The most output tokens one request may ask for (the runtime facade caps it). A request above
/// it is refused with a message; a default budget is clamped to it by the HTTP layer.
pub max_output_tokens: u32,
/// Wall-clock limit of one generation; the engine is cancelled when it expires.
pub generation_timeout: Option<Duration>,
/// No engine event for this long during a generation cancels it. Off by default: the text
@@ -92,16 +92,9 @@ enum Cancel {
Failure(String),
}
static NEXT_REQUEST: AtomicU64 = AtomicU64::new(1);
/// The runtime gRPC contract names a request by UUID and refuses a repeated one.
fn request_id() -> String {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
format!(
"strata-{nanos:x}-{:x}",
NEXT_REQUEST.fetch_add(1, Ordering::Relaxed)
)
uuid::Uuid::new_v4().to_string()
}
/// Run a blocking backend call off the async threads. The backend is `Send` but not `Sync`, so
@@ -181,6 +174,12 @@ async fn prepare(
if request.token_ids.is_empty() || request.max_new == 0 {
return Err("a generation needs prompt tokens and a positive max_new".to_owned());
}
if request.max_new > config.max_output_tokens {
return Err(format!(
"max_output_tokens {} exceeds the runtime's limit of {}",
request.max_new, config.max_output_tokens
));
}
let fixed = leleka_serving_policy::fixed::to_fixed_point(&request.sampling)
.map_err(|error| format!("sampling: {error}"))?;
let tokenizer = Arc::clone(&config.tokenizer);
@@ -285,6 +284,7 @@ pub async fn run_backend_worker(
};
attached_before = true;
update(&status, WorkerState::Ready, Some(config.max_context)).await;
status.write().await.output_cap = Some(config.max_output_tokens);
status.write().await.last_activity = Some(Instant::now());
for reply in waiting.drain(..) {
let _ = reply.send(Ok(()));
+68 -1
View File
@@ -27,6 +27,8 @@ pub struct Config {
pub bind: SocketAddr,
pub model: Option<String>,
pub worker: Option<WorkerConfig>,
/// Serve in front of a running `leleka-inference` instead of a stdio engine (`runtime` block).
pub runtime: Option<crate::runtime_config::RuntimeBackend>,
pub tokenizer_dir: Option<PathBuf>,
/// Other names the model answers to (`aliases`).
pub aliases: Vec<String>,
@@ -69,6 +71,7 @@ struct FileConfig {
bind: Option<String>,
model: Option<String>,
engine: Option<FileEngine>,
runtime: Option<crate::runtime_config::FileRuntime>,
aliases: Option<serde_json::Value>,
cors_origins: Option<serde_json::Value>,
trusted_origins: Option<serde_json::Value>,
@@ -383,7 +386,28 @@ impl Config {
}
tokenizer_dir = Some(native.output.join("tokenizer"));
}
if worker.is_none() && tokenizer_dir.is_some() {
if file.runtime.is_some() {
if worker.is_some() {
return Err("runtime and engine are mutually exclusive: the API serves in front of either a stdio engine child or a running leleka-inference".into());
}
if file.native_model.is_some()
|| file.mtp_pack.is_some()
|| file.vision.is_some()
|| file.gpu_requirement.is_some()
|| file.cuda_memory.is_some()
|| file.engine_probe
{
return Err("runtime cannot be combined with native_model, mtp_pack, vision, gpu_requirement, cuda_memory or engine_probe: the runtime process owns the model and the GPU".into());
}
}
let runtime = file
.runtime
.map(crate::runtime_config::FileRuntime::resolve)
.transpose()?;
if let Some(runtime) = &runtime {
tokenizer_dir.get_or_insert_with(|| runtime.tokenizer_dir.clone());
}
if worker.is_none() && runtime.is_none() && tokenizer_dir.is_some() {
return Err("tokenizer_dir requires an engine executable".into());
}
if worker.is_none() && file.gpu_requirement.is_some() {
@@ -558,6 +582,7 @@ impl Config {
bind,
model,
worker,
runtime,
tokenizer_dir,
})
}
@@ -767,6 +792,48 @@ mod tests {
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_runtime_block_excludes_every_way_of_starting_an_engine_itself() {
let dir = temp("runtime-exclusive");
let runtime = json!({
"address": "127.0.0.1:18766", "token_env": "LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS",
"tokenizer_dir": "/models/tokenizer",
"model": {"family": "f", "architecture": "a", "weight_format": "w",
"artifact_digest": format!("sha256:{}", "a".repeat(64))},
"mode": {"type": "native"}, "max_context": 4096
});
for (name, extra) in [
("engine", json!({"engine": {"executable": "/bin/e"}})),
("native_model", json!({"native_model": {}})),
("mtp_pack", json!({"mtp_pack": "/m"})),
("engine_probe", json!({"engine_probe": true})),
] {
let mut value = json!({"runtime": runtime});
for (key, item) in extra.as_object().unwrap() {
value[key] = item.clone();
}
let error = load(&dir, value).err().unwrap_or_default();
assert!(!error.is_empty(), "{name} must be refused");
}
// Alone it is accepted up to the credential, which comes from the environment.
let error = load(&dir, json!({"runtime": runtime})).err().unwrap();
assert!(
error.contains("LELEKA_RUNTIME_TOKEN_UNSET_IN_TESTS"),
"{error}"
);
let engine_error = load(
&dir,
json!({"runtime": runtime, "engine": {"executable": "/bin/e"}}),
)
.err()
.unwrap();
assert!(
engine_error.contains("mutually exclusive"),
"{engine_error}"
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_control_vector_becomes_engine_arguments_after_a_preflight() {
let dir = temp("cvec");
+1
View File
@@ -57,6 +57,7 @@ pub mod prepare_preview;
pub mod prompt;
mod response_tools;
pub mod responses;
pub mod runtime_config;
pub mod service_install;
pub mod service_unit;
pub mod stream_parts;
+44
View File
@@ -955,6 +955,47 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
state.vision = Some(strata_control::vision::Vision::start(vision).await?);
}
let (shutdown_tx, shutdown_rx) = watch::channel(false);
let runtime_task = match config.runtime.take() {
Some(runtime) => {
let tokenizer = state
.tokenizer
.clone()
.ok_or("runtime requires the tokenizer assets (runtime.tokenizer_dir)")?;
let (sender, receiver) = mpsc::channel(16);
let (control_sender, control_receiver) = mpsc::channel(16);
state.generation = Some(sender);
state.control = Some(control_sender);
state.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),
};
Some(tokio::spawn(
strata_control::backend_worker::run_backend_worker(
Box::new(backend),
worker_config,
state.worker.clone(),
shutdown_rx.clone(),
receiver,
control_receiver,
),
))
}
None => None,
};
let worker_task = config.worker.map(|mut config| {
config.vision = state.vision.clone();
let (sender, receiver) = mpsc::channel(16);
@@ -1009,6 +1050,9 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
if let Some(task) = worker_task {
task.await?;
}
if let Some(task) = runtime_task {
task.await?;
}
result?;
Ok(())
}
+13 -12
View File
@@ -1122,22 +1122,23 @@ pub async fn create(
Ok(prepared) => prepared,
Err(error) => return *error,
};
let remaining = state
.worker
.read()
.await
.max_context
.map(|context| {
context
.saturating_sub(token_ids.len())
.min(u32::MAX as usize) as u32
})
.unwrap_or(32768);
let (remaining, output_cap) = {
let worker = state.worker.read().await;
let remaining = worker
.max_context
.map(|context| {
context
.saturating_sub(token_ids.len())
.min(u32::MAX as usize) as u32
})
.unwrap_or(32768);
(remaining, worker.output_cap.unwrap_or(u32::MAX))
};
let generate = Generate {
token_ids,
max_new: request
.max_output_tokens
.unwrap_or(32768.min(remaining).max(1)),
.unwrap_or(32768.min(remaining).min(output_cap).max(1)),
sampling: request.sampling(),
tune: request.strata_tune.map(Into::into),
cvec: request.experimental_speed_projection,
+262
View File
@@ -0,0 +1,262 @@
//! The `runtime` block of the run configuration: serve the API in front of a `leleka-inference`
//! process that an operator already started and loaded (see `backend_worker`), instead of
//! supervising a stdio engine child (`engine`). The two are mutually exclusive.
//!
//! ```json
//! "runtime": {
//! "address": "127.0.0.1:18766",
//! "token_env": "LELEKA_RUNTIME_TOKEN",
//! "tokenizer_dir": "/models/tokenizer",
//! "model": {"family": "qwen4exp", "architecture": "qwen4exp", "weight_format": "gguf:iq3_s",
//! "artifact_digest": "sha256:..."},
//! "mode": {"type": "mtp", "profile_id": "qwen4exp-kar-ple-mtp-v1"},
//! "max_context": 262144
//! }
//! ```
//!
//! `model` and `mode` say what the runtime must have loaded; the worker attaches only if the runtime
//! reports exactly that, so a different artifact or inference path is never served by accident.
use std::{net::SocketAddr, path::PathBuf, time::Duration};
use leleka_backend_api as api;
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileRuntime {
address: String,
token_env: String,
tokenizer_dir: PathBuf,
model: FileModel,
mode: FileMode,
max_context: usize,
max_output_tokens: Option<u32>,
generation_timeout_s: Option<u64>,
stall_timeout_s: Option<u64>,
attach_retry_s: Option<f64>,
health_interval_s: Option<f64>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FileModel {
family: String,
architecture: String,
weight_format: String,
artifact_digest: String,
}
/// `{"type": "native"}`, `{"type": "kar_ple", "profile_id": ..}` or `{"type": "mtp", "profile_id": ..}`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FileMode {
r#type: String,
profile_id: Option<String>,
}
/// The validated block.
pub struct RuntimeBackend {
pub address: SocketAddr,
pub token: String,
pub tokenizer_dir: PathBuf,
pub model: api::ModelDescriptor,
pub runtime: api::RuntimeConfig,
pub max_context: usize,
pub max_output_tokens: u32,
pub generation_timeout: Option<Duration>,
pub stall_timeout: Option<Duration>,
pub attach_retry: Duration,
pub health_interval: Duration,
}
impl std::fmt::Debug for RuntimeBackend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeBackend")
.field("address", &self.address)
.field("token", &"[redacted]")
.field("model", &self.model)
.finish_non_exhaustive()
}
}
/// The output limit of the runtime gRPC facade today (`RuntimeServer::generate`).
pub const DEFAULT_MAX_OUTPUT_TOKENS: u32 = 4096;
fn seconds(name: &str, value: Option<f64>, default: f64) -> Result<Duration, String> {
let value = value.unwrap_or(default);
if !value.is_finite() || !(0.01..=3600.0).contains(&value) {
return Err(format!("runtime.{name} must be between 0.01 and 3600"));
}
Ok(Duration::from_secs_f64(value))
}
impl FileRuntime {
/// Read the credential from the environment and check every field. Nothing is connected to.
pub fn resolve(self) -> Result<RuntimeBackend, String> {
self.resolve_with(|name| std::env::var(name).ok())
}
fn resolve_with(self, env: impl Fn(&str) -> Option<String>) -> Result<RuntimeBackend, String> {
let address: SocketAddr = self
.address
.parse()
.map_err(|_| "runtime.address must be a literal ip:port".to_owned())?;
leleka_runtime_client::convert::literal_loopback(address)
.map_err(|_| "runtime.address must be a loopback address".to_owned())?;
let token = env(&self.token_env)
.ok_or_else(|| format!("runtime.token_env {} is not set", self.token_env))?;
if !leleka_runtime_client::convert::valid_token(&token) {
return Err(format!(
"{} must hold 32..4096 printable ASCII bytes",
self.token_env
));
}
let model = api::ModelDescriptor {
family: self.model.family,
architecture: self.model.architecture,
artifact_digest: self.model.artifact_digest,
weight_format: self.model.weight_format,
};
model
.validate()
.map_err(|error| format!("runtime.model: {error}"))?;
let (inference_mode, allow_experimental) =
match (self.mode.r#type.as_str(), self.mode.profile_id) {
("native", None) => (api::InferenceMode::Native, false),
("kar_ple", Some(profile_id)) => {
(api::InferenceMode::ExperimentalKarPle { profile_id }, true)
}
("mtp", Some(profile_id)) => {
(api::InferenceMode::ExperimentalMtp { profile_id }, true)
}
_ => {
return Err(
"runtime.mode must be native, or kar_ple / mtp with a profile_id".into(),
);
}
};
let runtime = api::RuntimeConfig {
load_config_version: api::LOAD_CONFIG_VERSION,
inference_mode,
gpu_memory_limit_bytes: None,
allow_experimental,
};
runtime
.validate()
.map_err(|error| format!("runtime.mode: {error}"))?;
if !(16..=(1 << 31)).contains(&self.max_context) {
return Err("runtime.max_context must be between 16 and 2147483648".into());
}
let max_output_tokens = self.max_output_tokens.unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS);
if max_output_tokens == 0
|| usize::try_from(max_output_tokens).is_ok_and(|n| n >= self.max_context)
{
return Err("runtime.max_output_tokens must be positive and below max_context".into());
}
for (name, value) in [
("generation_timeout_s", self.generation_timeout_s),
("stall_timeout_s", self.stall_timeout_s),
] {
if value.is_some_and(|seconds| !(1..=86_400).contains(&seconds)) {
return Err(format!("runtime.{name} must be between 1 and 86400"));
}
}
Ok(RuntimeBackend {
address,
token,
tokenizer_dir: self.tokenizer_dir,
model,
runtime,
max_context: self.max_context,
max_output_tokens,
generation_timeout: self.generation_timeout_s.map(Duration::from_secs),
stall_timeout: self.stall_timeout_s.map(Duration::from_secs),
attach_retry: seconds("attach_retry_s", self.attach_retry_s, 2.0)?,
health_interval: seconds("health_interval_s", self.health_interval_s, 2.0)?,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
const TOKEN: &str = "synthetic-runtime-config-token-0000000";
fn block() -> Value {
json!({
"address": "127.0.0.1:18766",
"token_env": "LELEKA_RUNTIME_TOKEN",
"tokenizer_dir": "/models/tokenizer",
"model": {"family": "qwen4exp", "architecture": "qwen4exp", "weight_format": "gguf:iq3_s",
"artifact_digest": format!("sha256:{}", "a".repeat(64))},
"mode": {"type": "mtp", "profile_id": "qwen4exp-kar-ple-mtp-v1"},
"max_context": 262144
})
}
fn resolve(value: Value) -> Result<RuntimeBackend, String> {
let parsed: FileRuntime = serde_json::from_value(value).map_err(|e| e.to_string())?;
parsed.resolve_with(|name| (name == "LELEKA_RUNTIME_TOKEN").then(|| TOKEN.to_owned()))
}
fn with(key: &str, value: Value) -> Value {
let mut block = block();
block[key] = value;
block
}
#[test]
fn a_complete_block_resolves_with_the_facade_defaults() {
let runtime = resolve(block()).unwrap();
assert_eq!(runtime.address.port(), 18766);
assert_eq!(runtime.token, TOKEN);
assert_eq!(runtime.max_output_tokens, DEFAULT_MAX_OUTPUT_TOKENS);
assert_eq!(
runtime.runtime.inference_mode,
api::InferenceMode::ExperimentalMtp {
profile_id: "qwen4exp-kar-ple-mtp-v1".into()
}
);
assert!(runtime.runtime.allow_experimental);
assert_eq!(runtime.attach_retry, Duration::from_secs(2));
let native = resolve(with("mode", json!({"type": "native"}))).unwrap();
assert!(!native.runtime.allow_experimental);
}
#[test]
fn refuses_what_would_attach_to_the_wrong_thing_or_leak_the_credential() {
for (key, value) in [
("address", json!("0.0.0.0:18766")),
("address", json!("localhost:18766")),
("address", json!("8.8.8.8:18766")),
("token_env", json!("NOT_SET_ANYWHERE")),
(
"mode",
json!({"type": "mtp", "profile_id": "somebody-elses-profile"}),
),
("mode", json!({"type": "kar_experts"})),
("mode", json!({"type": "native", "profile_id": "x"})),
("max_context", json!(8)),
("max_output_tokens", json!(0)),
("max_output_tokens", json!(262144)),
("generation_timeout_s", json!(0)),
("attach_retry_s", json!(0.0)),
] {
assert!(resolve(with(key, value.clone())).is_err(), "{key} {value}");
}
let mut bad_digest = block();
bad_digest["model"]["artifact_digest"] = json!("sha256:abc");
assert!(resolve(bad_digest).is_err());
// The token never appears in an error message.
let error = resolve(with("address", json!("nope"))).unwrap_err();
assert!(!error.contains(TOKEN));
// An unknown field is a typo, not an extension.
assert!(resolve(with("addres", json!("127.0.0.1:1"))).is_err());
// A weak credential is refused.
let parsed: FileRuntime = serde_json::from_value(block()).unwrap();
assert!(parsed.resolve_with(|_| Some("short".into())).is_err());
}
}
+5
View File
@@ -78,6 +78,10 @@ pub struct WorkerStatus {
/// When a request last started or finished, or the engine became ready.
pub last_activity: Option<tokio::time::Instant>,
pub metrics: crate::metrics::GenerationMetrics,
/// The most output tokens this engine accepts for one request, when it has its own limit (the
/// runtime gRPC facade does). A default output budget never exceeds it; an explicit request above
/// it is refused by the worker, not truncated.
pub output_cap: Option<u32>,
}
impl Default for WorkerStatus {
@@ -88,6 +92,7 @@ impl Default for WorkerStatus {
known_max_context: None,
last_activity: None,
metrics: Default::default(),
output_cap: None,
}
}
}
+9 -2
View File
@@ -119,6 +119,7 @@ impl Stack {
model: ScriptedEngine::fixture_descriptor(),
runtime: runtime_config(),
max_context: 262_144,
max_output_tokens: 4096,
health_interval: Duration::from_millis(20),
generation_timeout: None,
stall_timeout: None,
@@ -319,8 +320,13 @@ async fn non_streaming_text_carries_the_rendered_prompt_and_engine_usage() {
assert_eq!(sent.max_output_tokens, 64);
assert_eq!(sent.temperature_milli, 500);
assert_eq!(sent.sampling.seed, Some(7));
// The engine never sees the HTTP layer's token ids or the response ID.
assert!(sent.request_id.starts_with("strata-"));
// The engine never sees the HTTP layer's response ID; its own request identity is a UUID.
assert_eq!(sent.request_id.len(), 36);
assert!(
sent.request_id
.chars()
.all(|c| c == '-' || c.is_ascii_hexdigit())
);
stack.finish().await;
}
@@ -954,6 +960,7 @@ async fn a_prompt_that_is_not_the_canonical_encoding_is_refused() {
model: ScriptedEngine::fixture_descriptor(),
runtime: runtime_config(),
max_context: 262_144,
max_output_tokens: 4096,
health_interval: Duration::from_millis(20),
generation_timeout: None,
stall_timeout: None,