The Codex tic-tac-toe run (job 943) ended after 4 minutes: the model wrote the whole index.html in one tool call, hit the runtime's 4096-token output cap three times (tool call unterminated -> response.failed 'tool parameter is incomplete', then 'incomplete: max_output_tokens' -> turn.failed -> Codex exit 1). The Original server has no such cap (max_tokens 0 = the rest of the context). RuntimeServer, the engine request check, strata-next's runtime default, the leleka-deploy generated config and the examples now use leleka_backend_api::MAX_OUTPUT_TOKENS = 32768. /v1/status keeps the Python server's key set when no prefix cache exists (http_surface golden regressed with the prefix-cache merge). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
263 lines
10 KiB
Rust
263 lines
10 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: 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());
|
|
}
|
|
}
|