Files
leleka/control-plane/src/runtime_config.rs
T

293 lines
11 KiB
Rust

//! 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 = leleka_backend_api::MAX_OUTPUT_TOKENS;
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 = checked_address(&self.address)?;
let token = checked_token(&self.token_env, env)?;
let model = checked_model(self.model)?;
let runtime = checked_runtime(self.mode)?;
let max_output_tokens = checked_limits(
self.max_context,
self.max_output_tokens,
[self.generation_timeout_s, self.stall_timeout_s],
)?;
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)?,
})
}
}
fn checked_address(address: &str) -> Result<SocketAddr, String> {
let address: SocketAddr = 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())?;
Ok(address)
}
fn checked_token(token_env: &str, env: impl Fn(&str) -> Option<String>) -> Result<String, String> {
let token =
env(token_env).ok_or_else(|| format!("runtime.token_env {token_env} is not set"))?;
if !leleka_runtime_client::convert::valid_token(&token) {
return Err(format!(
"{token_env} must hold 32..4096 printable ASCII bytes"
));
}
Ok(token)
}
fn checked_model(file: FileModel) -> Result<api::ModelDescriptor, String> {
let model = api::ModelDescriptor {
family: file.family,
architecture: file.architecture,
artifact_digest: file.artifact_digest,
weight_format: file.weight_format,
};
model
.validate()
.map_err(|error| format!("runtime.model: {error}"))?;
Ok(model)
}
fn checked_runtime(mode: FileMode) -> Result<api::RuntimeConfig, String> {
let (inference_mode, allow_experimental) = match (mode.r#type.as_str(), 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}"))?;
Ok(runtime)
}
/// The context, output and timeout limits; returns the effective output limit.
fn checked_limits(
max_context: usize,
max_output_tokens: Option<u32>,
timeouts: [Option<u64>; 2],
) -> Result<u32, String> {
if !(16..=(1 << 31)).contains(&max_context) {
return Err("runtime.max_context must be between 16 and 2147483648".into());
}
let max_output_tokens = 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 >= max_context)
{
return Err("runtime.max_output_tokens must be positive and below max_context".into());
}
for (name, value) in ["generation_timeout_s", "stall_timeout_s"]
.into_iter()
.zip(timeouts)
{
if value.is_some_and(|seconds| !(1..=86_400).contains(&seconds)) {
return Err(format!("runtime.{name} must be between 1 and 86400"));
}
}
Ok(max_output_tokens)
}
#[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);
}
/// Values that would attach to the wrong thing or leak the credential: each key replaced by a bad value.
fn assert_bad_block_values_refused() {
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}");
}
}
#[test]
fn refuses_what_would_attach_to_the_wrong_thing_or_leak_the_credential() {
assert_bad_block_values_refused();
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());
}
}