Merge branch 'claude/szfn-dc' into claude/hexagonal-size-gw

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 19:06:17 +01:00
90 changed files with 7292 additions and 4731 deletions
+21 -19
View File
@@ -22,25 +22,9 @@ use leleka_runtime_client::{
use replay::{EngineMarks, InstantBackend};
use strata_desktop_core::runtime_rpc::RuntimeServer;
async fn grpc_backend(marks: Arc<EngineMarks>) -> Box<dyn api::Backend> {
let token = format!(
"fixture-runtime-credential-{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
);
let server =
RuntimeServer::new(Box::new(InstantBackend::new(marks)), token.clone()).expect("server");
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = server.serve(listener, std::future::pending::<()>()).await;
});
// what `leleka-cli load` does
let mut client = RuntimeClient::connect(address, token.clone())
.await
.unwrap();
/// What `leleka-cli load` does: one Load RPC for the current epoch, then wait for readiness.
async fn load_the_model(address: std::net::SocketAddr, token: String) {
let mut client = RuntimeClient::connect(address, token).await.unwrap();
let epoch = client.snapshot().await.unwrap().epoch;
client
.load(proto::LoadRequest {
@@ -61,6 +45,24 @@ async fn grpc_backend(marks: Arc<EngineMarks>) -> Box<dyn api::Backend> {
while !client.snapshot().await.unwrap().model_ready {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
}
async fn grpc_backend(marks: Arc<EngineMarks>) -> Box<dyn api::Backend> {
let token = format!(
"fixture-runtime-credential-{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
);
let server =
RuntimeServer::new(Box::new(InstantBackend::new(marks)), token.clone()).expect("server");
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = server.serve(listener, std::future::pending::<()>()).await;
});
load_the_model(address, token.clone()).await;
Box::new(GrpcBackend::new(
tokio::runtime::Handle::current(),
address,
+131 -158
View File
@@ -27,13 +27,13 @@ use leleka_runtime_client::{
convert::{config_to_proto, descriptor_to_proto},
proto,
};
use strata_control::{
reasoning_budget::Utf8Stream,
tokenizer::Tokenizer,
wire::{self, Event, Finish, Generate},
};
use strata_control::{reasoning_budget::Utf8Stream, tokenizer::Tokenizer, wire::Generate};
use strata_desktop_core::runtime_rpc::RuntimeServer;
#[path = "fake_runtime/pump.rs"]
mod pump;
use pump::{Active, Pump, exit_with_the_engine};
pub fn descriptor() -> api::ModelDescriptor {
api::ModelDescriptor {
family: "fixture_family".into(),
@@ -43,10 +43,6 @@ pub fn descriptor() -> api::ModelDescriptor {
}
}
struct Active {
id: String,
}
struct StdioTokenBackend {
exe: String,
args: Vec<String>,
@@ -66,6 +62,65 @@ fn failure(code: api::ErrorCode, message: &str) -> api::BackendError {
}
}
impl StdioTokenBackend {
/// Spawns the stdio engine and waits for its `READY` line.
fn spawn_ready_engine(
&self,
) -> Result<(Child, ChildStdin, BufReader<std::process::ChildStdout>), api::BackendError> {
let mut child = Command::new(&self.exe)
.arg("--serve")
.args(&self.args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(|e| failure(api::ErrorCode::BackendUnavailable, &e.to_string()))?;
let stdin = child.stdin.take().expect("piped stdin");
let mut stdout = BufReader::new(child.stdout.take().expect("piped stdout"));
loop {
let mut line = String::new();
if stdout.read_line(&mut line).unwrap_or(0) == 0 {
return Err(failure(
api::ErrorCode::BackendUnavailable,
"engine exited before READY",
));
}
if line.starts_with("READY") {
break;
}
}
Ok((child, stdin, stdout))
}
/// Marks the one generation slot busy for `request_id`.
fn reserve(&self, request_id: &str) -> Result<(), api::BackendError> {
let mut active = self.active.lock().unwrap();
if active.is_some() {
return Err(failure(api::ErrorCode::ResourceExhausted, "busy"));
}
*active = Some(Active {
id: request_id.to_string(),
});
Ok(())
}
/// The `GEN` line of a request.
fn generate_line(&self, request: &api::GenerationRequest) -> Result<String, api::BackendError> {
let ids = self
.tokenizer
.encode(&request.prompt, true)
.map_err(|e| failure(api::ErrorCode::InvalidRequest, &e.to_string()))?;
let generate = Generate {
token_ids: ids,
max_new: request.max_output_tokens,
..Default::default()
};
generate
.line()
.map_err(|e| failure(api::ErrorCode::InvalidRequest, e))
}
}
impl api::Backend for StdioTokenBackend {
fn identity(&self) -> api::BackendIdentity {
api::BackendIdentity {
@@ -104,41 +159,9 @@ impl api::Backend for StdioTokenBackend {
"unsupported model",
));
}
let mut child = Command::new(&self.exe)
.arg("--serve")
.args(&self.args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(|e| failure(api::ErrorCode::BackendUnavailable, &e.to_string()))?;
let stdin = child.stdin.take().expect("piped stdin");
let mut stdout = BufReader::new(child.stdout.take().expect("piped stdout"));
loop {
let mut line = String::new();
if stdout.read_line(&mut line).unwrap_or(0) == 0 {
return Err(failure(
api::ErrorCode::BackendUnavailable,
"engine exited before READY",
));
}
if line.starts_with("READY") {
break;
}
}
// The stand-in for leleka-inference *is* its engine: when the engine process dies, so does the
// fake runtime, as the real one would take its engine down with it.
let (child, stdin, stdout) = self.spawn_ready_engine()?;
let child = Arc::new(Mutex::new(child));
let watched = Arc::clone(&child);
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_millis(50));
if let Ok(Some(status)) = watched.lock().unwrap().try_wait() {
eprintln!("fake_runtime: the engine exited ({status}); exiting");
std::process::exit(2);
}
}
});
exit_with_the_engine(Arc::clone(&child));
self.child = Some(child);
self.stdin = Some(Arc::new(Mutex::new(stdin)));
self.lines = Some(Arc::new(Mutex::new(stdout)));
@@ -160,27 +183,8 @@ impl api::Backend for StdioTokenBackend {
let (Some(stdin), Some(lines)) = (self.stdin.clone(), self.lines.clone()) else {
return Err(failure(api::ErrorCode::BackendUnavailable, "not loaded"));
};
{
let mut active = self.active.lock().unwrap();
if active.is_some() {
return Err(failure(api::ErrorCode::ResourceExhausted, "busy"));
}
*active = Some(Active {
id: request.request_id.clone(),
});
}
let ids = self
.tokenizer
.encode(&request.prompt, true)
.map_err(|e| failure(api::ErrorCode::InvalidRequest, &e.to_string()))?;
let generate = Generate {
token_ids: ids,
max_new: request.max_output_tokens,
..Default::default()
};
let line = generate
.line()
.map_err(|e| failure(api::ErrorCode::InvalidRequest, e))?;
self.reserve(&request.request_id)?;
let line = self.generate_line(&request)?;
{
let mut pipe = stdin.lock().unwrap();
pipe.write_all(line.as_bytes())
@@ -188,63 +192,13 @@ impl api::Backend for StdioTokenBackend {
.map_err(|e| failure(api::ErrorCode::BackendUnavailable, &e.to_string()))?;
}
let (sink, stream) = api::GenerationSink::channel();
let tokenizer = Arc::clone(&self.tokenizer);
let active = Arc::clone(&self.active);
std::thread::spawn(move || {
let stops = ["<|im_end|>", "<|endoftext|>"].map(|s| tokenizer.special_id(s));
let mut utf8 = Utf8Stream::default();
let mut reader = lines.lock().unwrap();
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
*active.lock().unwrap() = None;
return; // the engine died: no terminal event
}
match wire::parse_line(&line) {
Ok(Some(Event::Token(id))) => {
if stops.contains(&Some(id)) {
continue; // the Rust engine never reports its stop token
}
let bytes = tokenizer.decode_bytes(&[id]).unwrap_or_default();
let text = utf8.push(&bytes);
if !text.is_empty()
&& sink.emit(api::GenerationEvent::TextDelta { text }).is_err()
{
*active.lock().unwrap() = None;
return;
}
}
Ok(Some(Event::Done(done))) => {
let tail = utf8.push(&[]);
if !tail.is_empty() {
let _ = sink.emit(api::GenerationEvent::TextDelta { text: tail });
}
*active.lock().unwrap() = None;
let usage = api::Usage {
input_tokens: done.prompt_tokens,
output_tokens: done.generated,
reused_input_tokens: done.reused.unwrap_or(0),
};
let _ = match done.finish {
Finish::Stop => sink.complete(api::FinishReason::Stop, usage),
Finish::Length => sink.complete(api::FinishReason::Length, usage),
Finish::Cancel => sink.cancel(),
};
return;
}
Ok(Some(Event::Error(message))) => {
*active.lock().unwrap() = None;
let _ = sink.fail(api::ErrorCode::Internal, message, false);
return;
}
Ok(Some(Event::PromptProgress { .. }) | None) => {}
Err(_) => {
*active.lock().unwrap() = None;
return;
}
}
}
});
let pump = Pump {
tokenizer: Arc::clone(&self.tokenizer),
active: Arc::clone(&self.active),
sink,
utf8: Utf8Stream::default(),
};
std::thread::spawn(move || pump.run(lines));
Ok(stream)
}
@@ -284,46 +238,19 @@ fn argument(args: &[String], name: &str) -> Option<String> {
.and_then(|i| args.get(i + 1).cloned())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().skip(1).collect();
let listen = argument(&args, "--listen").unwrap_or_else(|| "127.0.0.1:0".into());
let token_env = argument(&args, "--token-env").ok_or("--token-env is required")?;
let token = std::env::var(&token_env)?;
let exe = argument(&args, "--engine").ok_or("--engine is required")?;
let tokenizer_dir = argument(&args, "--tokenizer").ok_or("--tokenizer is required")?;
let engine_args: Vec<String> = args
.iter()
fn engine_arguments(args: &[String]) -> Vec<String> {
args.iter()
.enumerate()
.filter(|(i, a)| a.as_str() == "--engine-arg" && *i + 1 < args.len())
.map(|(i, _)| args[i + 1].clone())
.collect();
let tokenizer = Arc::new(Tokenizer::from_assets(std::path::Path::new(
&tokenizer_dir,
))?);
let backend = StdioTokenBackend {
exe,
args: engine_args,
tokenizer,
child: None,
stdin: None,
lines: None,
ready: false,
active: Arc::new(Mutex::new(None)),
};
let server =
RuntimeServer::new(Box::new(backend), token.clone()).map_err(|e| e.message().to_owned())?;
let listener = tokio::net::TcpListener::bind(&listen).await?;
let address = listener.local_addr()?;
let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
let serving = tokio::spawn(async move {
let _ = server
.serve(listener, async {
let _ = stopped.await;
})
.await;
});
// What `leleka-cli load` does: one Load RPC for the current epoch.
.collect()
}
/// What `leleka-cli load` does: one Load RPC for the current epoch, then wait for readiness.
async fn load_the_model(
address: std::net::SocketAddr,
token: String,
) -> Result<(), Box<dyn std::error::Error>> {
let mut client = RuntimeClient::connect(address, token).await?;
let epoch = client.snapshot().await?.epoch;
client
@@ -342,6 +269,52 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
while !client.snapshot().await?.model_ready {
tokio::time::sleep(Duration::from_millis(10)).await;
}
Ok(())
}
type Failure = Box<dyn std::error::Error>;
/// The backend and the `--listen` / token settings the command line asks for.
fn backend_from_args(args: &[String]) -> Result<(StdioTokenBackend, String, String), Failure> {
let listen = argument(args, "--listen").unwrap_or_else(|| "127.0.0.1:0".into());
let token_env = argument(args, "--token-env").ok_or("--token-env is required")?;
let token = std::env::var(&token_env)?;
let exe = argument(args, "--engine").ok_or("--engine is required")?;
let tokenizer_dir = argument(args, "--tokenizer").ok_or("--tokenizer is required")?;
let engine_args = engine_arguments(args);
let tokenizer = Arc::new(Tokenizer::from_assets(std::path::Path::new(
&tokenizer_dir,
))?);
let backend = StdioTokenBackend {
exe,
args: engine_args,
tokenizer,
child: None,
stdin: None,
lines: None,
ready: false,
active: Arc::new(Mutex::new(None)),
};
Ok((backend, listen, token))
}
#[tokio::main]
async fn main() -> Result<(), Failure> {
let args: Vec<String> = std::env::args().skip(1).collect();
let (backend, listen, token) = backend_from_args(&args)?;
let server =
RuntimeServer::new(Box::new(backend), token.clone()).map_err(|e| e.message().to_owned())?;
let listener = tokio::net::TcpListener::bind(&listen).await?;
let address = listener.local_addr()?;
let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
let serving = tokio::spawn(async move {
let _ = server
.serve(listener, async {
let _ = stopped.await;
})
.await;
});
load_the_model(address, token).await?;
println!("LISTENING {address}");
std::io::stdout().flush()?;
// Serve until the parent closes our stdin or kills us.
+116
View File
@@ -0,0 +1,116 @@
//! The generation pump of the fake runtime: engine output lines to generation events.
use std::{
io::{BufRead, BufReader},
process::Child,
sync::{Arc, Mutex},
time::Duration,
};
use leleka_backend_api as api;
use strata_control::{
reasoning_budget::Utf8Stream,
tokenizer::Tokenizer,
wire::{self, Event, Finish},
};
pub(super) struct Active {
pub(super) id: String,
}
/// The stand-in for leleka-inference *is* its engine: when the engine process dies, so does the
/// fake runtime, as the real one would take its engine down with it.
pub(super) fn exit_with_the_engine(watched: Arc<Mutex<Child>>) {
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_millis(50));
if let Ok(Some(status)) = watched.lock().unwrap().try_wait() {
eprintln!("fake_runtime: the engine exited ({status}); exiting");
std::process::exit(2);
}
}
});
}
/// Turns the engine's output lines into generation events until a terminal event or an error.
pub(super) struct Pump {
pub(super) tokenizer: Arc<Tokenizer>,
pub(super) active: Arc<Mutex<Option<Active>>>,
pub(super) sink: api::GenerationSink,
pub(super) utf8: Utf8Stream,
}
impl Pump {
pub(super) fn run(mut self, lines: Arc<Mutex<BufReader<std::process::ChildStdout>>>) {
let stops = ["<|im_end|>", "<|endoftext|>"].map(|s| self.tokenizer.special_id(s));
let mut reader = lines.lock().unwrap();
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
self.release();
return; // the engine died: no terminal event
}
let finished = match wire::parse_line(&line) {
Ok(Some(Event::Token(id))) => self.token(id, &stops),
Ok(Some(Event::Done(done))) => self.done(done),
Ok(Some(Event::Error(message))) => {
self.release();
let _ = self.sink.fail(api::ErrorCode::Internal, message, false);
true
}
Ok(Some(Event::PromptProgress { .. }) | None) => false,
Err(_) => {
self.release();
true
}
};
if finished {
return;
}
}
}
fn release(&self) {
*self.active.lock().unwrap() = None;
}
/// Forwards one token as text; true when the consumer is gone.
fn token(&mut self, id: u32, stops: &[Option<u32>]) -> bool {
if stops.contains(&Some(id)) {
return false; // the Rust engine never reports its stop token
}
let bytes = self.tokenizer.decode_bytes(&[id]).unwrap_or_default();
let text = self.utf8.push(&bytes);
if !text.is_empty()
&& self
.sink
.emit(api::GenerationEvent::TextDelta { text })
.is_err()
{
self.release();
return true;
}
false
}
fn done(&mut self, done: wire::Done) -> bool {
let tail = self.utf8.push(&[]);
if !tail.is_empty() {
let _ = self
.sink
.emit(api::GenerationEvent::TextDelta { text: tail });
}
self.release();
let usage = api::Usage {
input_tokens: done.prompt_tokens,
output_tokens: done.generated,
reused_input_tokens: done.reused.unwrap_or(0),
};
let _ = match done.finish {
Finish::Stop => self.sink.complete(api::FinishReason::Stop, usage),
Finish::Length => self.sink.complete(api::FinishReason::Length, usage),
Finish::Cancel => self.sink.cancel(),
};
true
}
}
+192 -109
View File
@@ -3,118 +3,197 @@ use serde_json::{Value, json};
use std::{path::Path, time::Duration};
use strata_desktop_core::runtime_gateway::Config;
type Failure = Box<dyn std::error::Error>;
/// The daemon route of a command and the JSON body it posts (none: a GET).
type Route = (&'static str, Option<Value>);
const HELP: &str = concat!(
"leleka-cli --config PATH validate|models|status|load MODEL native|load MODEL kar-ple PROFILE|",
"load-mtp MODEL PROFILE|unload MODEL|operation MODEL UUID EPOCH\n",
"MTP profiles: qwen4exp-native-mtp-v1 or qwen4exp-kar-ple-mtp-v1 (experimental). ",
"Load and unload print an operation UUID before sending. ",
"They never retry uncertain commands; query that UUID with operation."
);
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn main() -> Result<(), Failure> {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.as_slice() == ["--help"] {
println!(
"leleka-cli --config PATH validate|models|status|load MODEL native|load MODEL kar-ple PROFILE|load-mtp MODEL PROFILE|unload MODEL|operation MODEL UUID EPOCH\nMTP profiles: qwen4exp-native-mtp-v1 or qwen4exp-kar-ple-mtp-v1 (experimental). Load and unload print an operation UUID before sending. They never retry uncertain commands; query that UUID with operation."
);
println!("{HELP}");
return Ok(());
}
if args.len() < 3 || args[0] != "--config" {
return Err("invalid_cli_arguments".into());
}
let config = Config::read(Path::new(&args[1]))?;
run(&args).await
}
async fn run(args: &[String]) -> Result<(), Failure> {
let config = read_config(args)?;
let command: Vec<&str> = args[2..].iter().map(String::as_str).collect();
if command.as_slice() == ["validate"] {
println!("configuration_valid");
return Ok(());
}
if command.first() == Some(&"load-mtp")
&& !matches!(
command.as_slice(),
[
"load-mtp",
_,
"qwen4exp-native-mtp-v1" | "qwen4exp-kar-ple-mtp-v1"
]
)
{
return Err("invalid_mtp_profile".into());
}
let token = config.credential()?;
let client = reqwest::Client::builder()
.no_proxy()
.timeout(Duration::from_secs(10))
.build()?;
let base = format!("http://{}", config.listen);
let (route, body) = match command.as_slice() {
["models"] => ("/v1/models", None),
["status"] => ("/runtime/status", None),
["operation", model, id, epoch] => {
uuid::Uuid::parse_str(id).map_err(|_| "invalid_operation_id")?;
uuid::Uuid::parse_str(epoch).map_err(|_| "invalid_epoch")?;
(
"/runtime/operation",
Some(json!({"model":model,"operation_id":id,"epoch":epoch})),
)
}
["load", model, "native"]
| ["load", model, "kar-ple", _]
| ["load-mtp", model, _]
| ["unload", model] => {
if !config.runtimes.iter().any(|m| m.id == *model) {
return Err("unknown_model".into());
}
let state = request(&client, &base, &token, "/runtime/status", None).await?;
let epoch = state["runtimes"]
.as_array()
.and_then(|states| states.iter().find(|s| s["id"] == *model))
.and_then(|s| s["epoch"].as_str())
.ok_or("runtime_not_connected")?;
let id = uuid::Uuid::new_v4().to_string();
// Operator can reconcile this exact command even if the response is lost.
println!("{}", json!({"operation_id":id,"epoch":epoch,"model":model}));
let mut body = json!({"model":model,"operation_id":id,"epoch":epoch});
let route = if matches!(command[0], "load" | "load-mtp") {
if command[0] == "load-mtp" {
body["mode"] = json!("mtp");
body["profile_id"] = json!(command[2]);
} else {
body["mode"] = json!(command[2]);
if command[2] == "kar-ple" {
body["profile_id"] = json!(command[3]);
}
}
"/runtime/load"
} else {
let handle = state["runtimes"]
.as_array()
.and_then(|states| states.iter().find(|s| s["id"] == *model))
.and_then(|s| s["loaded_handle"].as_str())
.ok_or("model_not_loaded")?;
body["handle"] = json!(handle);
"/runtime/unload"
};
(route, Some(body))
}
_ => return Err("invalid_cli_arguments".into()),
};
let result = request(&client, &base, &token, route, body).await?;
check_mtp_profile(&command)?;
let link = DaemonLink::new(&config)?;
let (route, body) = command_route(&link, &config, &command).await?;
let result = link.request(route, body).await?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
async fn request(
client: &reqwest::Client,
base: &str,
token: &str,
route: &str,
body: Option<Value>,
) -> Result<Value, Box<dyn std::error::Error>> {
let mut request = match body {
Some(body) => client
.post(format!("{base}{route}"))
.header("content-type", "application/json")
.body(serde_json::to_vec(&body)?),
None => client.get(format!("{base}{route}")),
};
request = request.bearer_auth(token);
let response = request
.send()
.await
.map_err(|_| "daemon_request_outcome_unknown")?;
let status = response.status();
fn read_config(args: &[String]) -> Result<Config, Failure> {
if args.len() < 3 || args[0] != "--config" {
return Err("invalid_cli_arguments".into());
}
Ok(Config::read(Path::new(&args[1]))?)
}
fn check_mtp_profile(command: &[&str]) -> Result<(), Failure> {
let known = matches!(
command,
[
"load-mtp",
_,
"qwen4exp-native-mtp-v1" | "qwen4exp-kar-ple-mtp-v1"
]
);
if command.first() == Some(&"load-mtp") && !known {
return Err("invalid_mtp_profile".into());
}
Ok(())
}
/// The route and body a command maps to.
async fn command_route(
link: &DaemonLink,
config: &Config,
command: &[&str],
) -> Result<Route, Failure> {
match command {
["models"] => Ok(("/v1/models", None)),
["status"] => Ok(("/runtime/status", None)),
["operation", model, id, epoch] => operation_route(model, id, epoch),
["load", model, "native"]
| ["load", model, "kar-ple", _]
| ["load-mtp", model, _]
| ["unload", model] => runtime_command(link, config, command, model).await,
_ => Err("invalid_cli_arguments".into()),
}
}
fn operation_route(model: &str, id: &str, epoch: &str) -> Result<Route, Failure> {
uuid::Uuid::parse_str(id).map_err(|_| "invalid_operation_id")?;
uuid::Uuid::parse_str(epoch).map_err(|_| "invalid_epoch")?;
Ok((
"/runtime/operation",
Some(json!({"model":model,"operation_id":id,"epoch":epoch})),
))
}
/// A load or unload: names an operation id first, so the operator can reconcile a lost response.
async fn runtime_command(
link: &DaemonLink,
config: &Config,
command: &[&str],
model: &str,
) -> Result<Route, Failure> {
if !config.runtimes.iter().any(|m| m.id == model) {
return Err("unknown_model".into());
}
let state = link.request("/runtime/status", None).await?;
let epoch = runtime_field(&state, model, "epoch", "runtime_not_connected")?;
let id = uuid::Uuid::new_v4().to_string();
// Operator can reconcile this exact command even if the response is lost.
println!("{}", json!({"operation_id":id,"epoch":epoch,"model":model}));
let mut body = json!({"model":model,"operation_id":id,"epoch":epoch});
if matches!(command[0], "load" | "load-mtp") {
add_load_fields(&mut body, command);
return Ok(("/runtime/load", Some(body)));
}
let handle = runtime_field(&state, model, "loaded_handle", "model_not_loaded")?;
body["handle"] = json!(handle);
Ok(("/runtime/unload", Some(body)))
}
/// A string field of the status entry of runtime `model`.
fn runtime_field<'a>(
state: &'a Value,
model: &str,
field: &str,
fault: &'static str,
) -> Result<&'a str, &'static str> {
state["runtimes"]
.as_array()
.and_then(|states| states.iter().find(|s| s["id"] == model))
.and_then(|s| s[field].as_str())
.ok_or(fault)
}
fn add_load_fields(body: &mut Value, command: &[&str]) {
if command[0] == "load-mtp" {
body["mode"] = json!("mtp");
body["profile_id"] = json!(command[2]);
} else {
body["mode"] = json!(command[2]);
if command[2] == "kar-ple" {
body["profile_id"] = json!(command[3]);
}
}
}
/// The HTTP client, base URL and credential of the local daemon.
struct DaemonLink {
client: reqwest::Client,
base: String,
token: String,
}
impl DaemonLink {
fn new(config: &Config) -> Result<Self, Failure> {
let token = config.credential()?;
let client = reqwest::Client::builder()
.no_proxy()
.timeout(Duration::from_secs(10))
.build()?;
let base = format!("http://{}", config.listen);
Ok(Self {
client,
base,
token,
})
}
async fn request(&self, route: &str, body: Option<Value>) -> Result<Value, Failure> {
let response = self.send(route, body).await?;
let status = response.status();
let bytes = read_limited(response).await?;
let value: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid_daemon_response")?;
if !status.is_success() {
report_failure(status, &value);
return Err("daemon_command_failed".into());
}
Ok(value)
}
async fn send(&self, route: &str, body: Option<Value>) -> Result<reqwest::Response, Failure> {
let url = format!("{}{route}", self.base);
let request = match body {
Some(body) => self
.client
.post(url)
.header("content-type", "application/json")
.body(serde_json::to_vec(&body)?),
None => self.client.get(url),
};
Ok(request
.bearer_auth(&self.token)
.send()
.await
.map_err(|_| "daemon_request_outcome_unknown")?)
}
}
/// The response body, at most 1 MiB.
async fn read_limited(response: reqwest::Response) -> Result<Vec<u8>, Failure> {
use futures_util::StreamExt;
let mut stream = response.bytes_stream();
let mut bytes = Vec::new();
@@ -125,14 +204,18 @@ async fn request(
}
bytes.extend_from_slice(&chunk);
}
let value: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid_daemon_response")?;
if !status.is_success() {
// Only fixed error fields from our authenticated daemon, no server diagnostics.
println!(
"{}",
json!({"http_status":status.as_u16(),"operation_id":value.get("operation_id"),"epoch":value.get("epoch"),"state":value.get("state")})
);
return Err("daemon_command_failed".into());
}
Ok(value)
Ok(bytes)
}
/// Only fixed error fields from our authenticated daemon, no server diagnostics.
fn report_failure(status: reqwest::StatusCode, value: &Value) {
println!(
"{}",
json!({
"http_status": status.as_u16(),
"operation_id": value.get("operation_id"),
"epoch": value.get("epoch"),
"state": value.get("state"),
})
);
}
+22 -10
View File
@@ -18,22 +18,38 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::read(Path::new(path))?;
let listener = tokio::net::TcpListener::bind(config.listen).await?;
let registry = Registry::new(config)?;
let monitor = registry.clone();
let monitor = tokio::spawn(async move {
let monitor = spawn_monitor(registry.clone());
let result = serve_until_stopped(listener, &registry).await;
monitor.abort();
let _ = monitor.await;
result?;
Ok(())
}
/// Refresh the runtimes every five seconds until aborted.
fn spawn_monitor(monitor: Registry) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(5));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
interval.tick().await;
monitor.refresh().await;
}
});
})
}
/// Serve until the stop signal, then give the open streams ten seconds to drain.
async fn serve_until_stopped(
listener: tokio::net::TcpListener,
registry: &Registry,
) -> std::io::Result<()> {
let (stop, stopped) = tokio::sync::oneshot::channel();
let serving = axum::serve(listener, registry.router()).with_graceful_shutdown(async {
let _ = stopped.await;
});
let serving = std::future::IntoFuture::into_future(serving);
tokio::pin!(serving);
let result = tokio::select! {
tokio::select! {
result = &mut serving => result,
_ = stop_signal() => {
let _ = stop.send(());
@@ -44,14 +60,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Err(_) => Ok(()),
}
}
};
monitor.abort();
let _ = monitor.await;
result?;
Ok(())
}
}
/// Ctrl-C everywhere; on Windows also Ctrl-Break, which is how `leleka run` asks a child (they run in their own process
// Ctrl-C everywhere; on Windows also Ctrl-Break, which is how `leleka run` asks a child (they run in their own process
/// groups, where Ctrl-C is not delivered) to drain and stop.
async fn stop_signal() {
#[cfg(windows)]
@@ -1,4 +1,5 @@
//! Linux CUDA inference process. Operator-owned artifact paths never enter RPCs.
use leleka_backend_api::Backend;
use leleka_runtime::backend::{
InheritedKarArchive, NativeBackendConfig, spawn_backend_observed,
spawn_backend_observed_native_integer_iq3_windowed256_retained_gr,
@@ -9,71 +10,108 @@ use strata_desktop_core::runtime_rpc::RuntimeServer;
#[path = "../evaluation_measurement.rs"]
mod evaluation_measurement;
const HELP: &str = concat!(
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ",
"ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | ",
"--kar-archive-fd N --kar-provenance PATH] [--mtp-pack PATH --mtp-staging PATH]",
);
type Failure = Box<dyn std::error::Error>;
/// The seven `--flag VALUE` pairs every start carries, in this order.
struct BaseArguments<'a> {
address: &'a str,
token_env: &'a str,
shard0: &'a str,
shard1: &'a str,
gpu: &'a str,
budget: &'a str,
context: &'a str,
}
const BASE_FLAGS: [&str; 7] = [
"--listen",
"--token-env",
"--shard0",
"--shard1",
"--gpu",
"--gpu-budget",
"--context-tokens",
];
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn main() -> Result<(), Failure> {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.as_slice() == ["--help"] {
println!(
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH] [--mtp-pack PATH --mtp-staging PATH]"
);
println!("{HELP}");
return Ok(());
}
let (base, extra) = if args.len() >= 14 {
args.split_at(14)
} else {
return Err("invalid_inference_arguments".into());
};
let sources = operator_sources_with_inherited(extra)?;
let [
l,
address,
t,
token_env,
s0,
shard0,
s1,
shard1,
g,
gpu,
b,
budget,
c,
context,
] = base
else {
return Err("invalid_inference_arguments".into());
};
if l != "--listen"
|| t != "--token-env"
|| s0 != "--shard0"
|| s1 != "--shard1"
|| g != "--gpu"
|| b != "--gpu-budget"
|| c != "--context-tokens"
{
if args.len() < 14 {
return Err("invalid_inference_arguments".into());
}
let address: SocketAddr = address.parse().map_err(|_| "invalid_runtime_endpoint")?;
let (base, extra) = args.split_at(14);
let sources = operator_sources_with_inherited(extra)?;
let base = base_arguments(base)?;
let address = listen_address(base.address)?;
let token = runtime_credential(base.token_env)?;
let config = native_config(&base, sources)?;
let backend = spawn_observed(config)?;
serve(backend, token, address).await
}
fn flags_in_order(base: &[String]) -> bool {
let flags = BASE_FLAGS.iter().enumerate();
base.len() == 14
&& flags
.into_iter()
.all(|(index, flag)| base[2 * index] == *flag)
}
fn base_arguments(base: &[String]) -> Result<BaseArguments<'_>, Failure> {
if !flags_in_order(base) {
return Err("invalid_inference_arguments".into());
}
Ok(BaseArguments {
address: &base[1],
token_env: &base[3],
shard0: &base[5],
shard1: &base[7],
gpu: &base[9],
budget: &base[11],
context: &base[13],
})
}
fn listen_address(text: &str) -> Result<SocketAddr, Failure> {
let address: SocketAddr = text.parse().map_err(|_| "invalid_runtime_endpoint")?;
if !address.ip().is_loopback() {
return Err("loopback_required".into());
}
if token_env.is_empty()
|| !token_env
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
{
Ok(address)
}
/// The runtime credential, read from the environment variable `name`.
fn runtime_credential(name: &str) -> Result<String, Failure> {
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return Err("invalid_token_environment_name".into());
}
let token = std::env::var(token_env).map_err(|_| "missing_runtime_credential")?;
let token = std::env::var(name).map_err(|_| "missing_runtime_credential")?;
if !(32..=4096).contains(&token.len()) || !token.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
return Err("invalid_runtime_credential".into());
}
let config = NativeBackendConfig {
shard0: PathBuf::from(shard0),
shard1: PathBuf::from(shard1),
gpu_device_ordinal: gpu.parse().map_err(|_| "invalid_gpu_ordinal")?,
gpu_budget_bytes: budget.parse().map_err(|_| "invalid_gpu_budget")?,
context_tokens: context.parse().map_err(|_| "invalid_context_bound")?,
Ok(token)
}
fn native_config(
base: &BaseArguments<'_>,
sources: OperatorSources,
) -> Result<NativeBackendConfig, Failure> {
Ok(NativeBackendConfig {
shard0: PathBuf::from(base.shard0),
shard1: PathBuf::from(base.shard1),
gpu_device_ordinal: base.gpu.parse().map_err(|_| "invalid_gpu_ordinal")?,
gpu_budget_bytes: base.budget.parse().map_err(|_| "invalid_gpu_budget")?,
context_tokens: base.context.parse().map_err(|_| "invalid_context_bound")?,
kar_ple_source: sources.kar,
kar_ple_inherited: sources
.inherited
@@ -82,7 +120,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
mtp_source: sources.mtp,
kar_expert_source: None,
experimental: Default::default(),
};
})
}
/// Start the engine with the observer of the evaluation policy named by the environment.
fn spawn_observed(config: NativeBackendConfig) -> Result<Box<dyn Backend>, Failure> {
let policy = evaluation_measurement::EvaluationPolicy::from_environment()?;
let observer = evaluation_measurement::observer(policy)?;
let backend = match policy {
@@ -98,9 +140,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
evaluation_measurement::EvaluationPolicy::NativeIntegerIq3Windowed256RetainedGr => {
spawn_backend_observed_native_integer_iq3_windowed256_retained_gr(config, observer)
}
}
.map_err(|_| "runtime_startup_failed")?;
let server = RuntimeServer::new(backend, token.clone())?;
};
Ok(backend.map_err(|_| "runtime_startup_failed")?)
}
async fn serve(
backend: Box<dyn Backend>,
token: String,
address: SocketAddr,
) -> Result<(), Failure> {
let server = RuntimeServer::new(backend, token)?;
let listener = tokio::net::TcpListener::bind(address).await?;
// Transport starts closed for model admission. Loading is an explicit typed
// lifecycle command; successful configuration parsing is never model ready.
@@ -129,21 +178,7 @@ fn operator_sources_with_inherited(args: &[String]) -> Result<OperatorSources, &
let mut ordinary = Vec::with_capacity(args.len());
for pair in args.as_chunks::<4>().0 {
if pair[0] == "--kar-archive-fd" {
if inherited.is_some()
|| pair[2] != "--kar-provenance"
|| pair[1].is_empty()
|| !pair[1].bytes().all(|b| b.is_ascii_digit())
|| pair[3].is_empty()
{
return Err("invalid_inherited_kar_arguments");
}
let fd: u32 = pair[1]
.parse()
.map_err(|_| "invalid_inherited_kar_arguments")?;
if !(3..=1_048_576).contains(&fd) {
return Err("invalid_inherited_kar_arguments");
}
inherited = Some((fd, PathBuf::from(&pair[3])));
inherited = Some(inherited_pair(pair, inherited.is_some())?);
} else {
ordinary.extend_from_slice(pair);
}
@@ -159,6 +194,24 @@ fn operator_sources_with_inherited(args: &[String]) -> Result<OperatorSources, &
})
}
/// `--kar-archive-fd N --kar-provenance PATH`: a descriptor in 3..=1048576 and the provenance path.
fn inherited_pair(pair: &[String; 4], taken: bool) -> Result<(u32, PathBuf), &'static str> {
const FAULT: &str = "invalid_inherited_kar_arguments";
if taken
|| pair[2] != "--kar-provenance"
|| pair[1].is_empty()
|| !pair[1].bytes().all(|b| b.is_ascii_digit())
|| pair[3].is_empty()
{
return Err(FAULT);
}
let fd: u32 = pair[1].parse().map_err(|_| FAULT)?;
if !(3..=1_048_576).contains(&fd) {
return Err(FAULT);
}
Ok((fd, PathBuf::from(&pair[3])))
}
fn operator_sources(args: &[String]) -> Result<(OperatorSource, OperatorSource), &'static str> {
let mut kar = None;
let mut mtp = None;
@@ -168,12 +221,7 @@ fn operator_sources(args: &[String]) -> Result<(OperatorSource, OperatorSource),
for pair in args.as_chunks::<4>().0 {
match pair[0].as_str() {
"--kar-archive" if kar.is_none() => kar = kar_source(pair)?,
"--mtp-pack"
if mtp.is_none()
&& pair[2] == "--mtp-staging"
&& !pair[1].is_empty()
&& !pair[3].is_empty() =>
{
"--mtp-pack" if mtp.is_none() && mtp_pair_is_closed(pair) => {
mtp = Some((PathBuf::from(&pair[1]), PathBuf::from(&pair[3])));
}
_ => return Err("invalid_operator_source_pairs"),
@@ -182,6 +230,11 @@ fn operator_sources(args: &[String]) -> Result<(OperatorSource, OperatorSource),
Ok((kar, mtp))
}
/// `--mtp-pack PATH --mtp-staging PATH` with both paths non-empty.
fn mtp_pair_is_closed(pair: &[String; 4]) -> bool {
pair[2] == "--mtp-staging" && !pair[1].is_empty() && !pair[3].is_empty()
}
fn kar_source(args: &[String]) -> Result<Option<(PathBuf, PathBuf)>, &'static str> {
match args {
[] => Ok(None),
@@ -201,44 +254,44 @@ fn kar_source(args: &[String]) -> Result<Option<(PathBuf, PathBuf)>, &'static st
mod inherited_source_tests {
use super::*;
#[test]
fn inherited_kar_pair_is_bounded_exclusive_and_keeps_mtp_independent() {
let inherited =
["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from);
let mtp = ["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from);
fn inherited_fd() -> [String; 4] {
["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from)
}
fn mtp_pair() -> [String; 4] {
["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from)
}
fn joined(first: &[String], second: &[String]) -> Vec<String> {
first.iter().chain(second).cloned().collect()
}
fn assert_either_order_keeps_mtp_independent(inherited: &[String], mtp: &[String]) {
let expected = OperatorSources {
kar: None,
mtp: Some(("pack".into(), "private".into())),
inherited: Some((9, "proof.json".into())),
};
for args in [
inherited.iter().chain(&mtp).cloned().collect::<Vec<_>>(),
mtp.iter().chain(&inherited).cloned().collect(),
] {
for args in [joined(inherited, mtp), joined(mtp, inherited)] {
assert_eq!(operator_sources_with_inherited(&args).unwrap(), expected);
}
}
fn assert_exclusive(inherited: &[String]) {
let kar = ["--kar-archive", "archive", "--kar-staging", "private"].map(String::from);
assert!(
operator_sources_with_inherited(
&inherited.iter().chain(&kar).cloned().collect::<Vec<_>>()
)
.is_err()
);
assert!(
operator_sources_with_inherited(
&inherited
.iter()
.chain(&inherited)
.cloned()
.collect::<Vec<_>>()
)
.is_err()
);
assert!(operator_sources_with_inherited(&joined(inherited, &kar)).is_err());
assert!(operator_sources_with_inherited(&joined(inherited, inherited)).is_err());
}
fn assert_descriptor_bounded(inherited: &[String; 4]) {
for fd in ["", "0", "1", "2", "-3", "+9", " 9", "1048577", "4294967296"] {
let mut invalid = inherited.clone();
invalid[1] = fd.into();
assert!(operator_sources_with_inherited(&invalid).is_err());
}
}
fn assert_malformed_refused(inherited: &[String; 4]) {
for length in [1, 2, 3] {
assert!(operator_sources_with_inherited(&inherited[..length]).is_err());
}
@@ -248,6 +301,15 @@ mod inherited_source_tests {
invalid[2] = "--kar-provenance".into();
invalid[3].clear();
assert!(operator_sources_with_inherited(&invalid).is_err());
}
#[test]
fn inherited_kar_pair_is_bounded_exclusive_and_keeps_mtp_independent() {
let inherited = inherited_fd();
assert_either_order_keeps_mtp_independent(&inherited, &mtp_pair());
assert_exclusive(&inherited);
assert_descriptor_bounded(&inherited);
assert_malformed_refused(&inherited);
assert_eq!(
operator_sources_with_inherited(&[]).unwrap(),
OperatorSources {
@@ -9,13 +9,13 @@ pub(super) fn operator_adaptive_slots_execution(
args,
ADAPTIVE_SLOTS_FLAG,
&[
RESIDENT_OWNERS_FLAG,
RETAINED_SCRATCH_FLAG,
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
],
RESIDENT_OWNERS_FLAG,
RETAINED_SCRATCH_FLAG,
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
],
"duplicate_retained_scratch_execution_flag",
RESIDENT_OWNERS_FLAG,
)
@@ -51,7 +51,8 @@ pub(super) fn select_execution_flag(
duplicate: &'static str,
replacement: &str,
) -> Result<(bool, Vec<String>), &'static str> {
let (selected, other_selection, mut ordinary) = scan_execution_flag(args, flag, others, duplicate)?;
let (selected, other_selection, mut ordinary) =
scan_execution_flag(args, flag, others, duplicate)?;
if selected {
if other_selection {
return Err("conflicting_experimental_execution_flags");
@@ -92,10 +93,9 @@ fn scan_execution_flag(
}
/// The four-item source tuple that starts at `offset`.
fn source_tuple(args: &[String], offset: usize) -> Result<&[String], &'static str> {
pub(super) fn source_tuple(args: &[String], offset: usize) -> Result<&[String], &'static str> {
let end = offset
.checked_add(4)
.ok_or("invalid_operator_source_pairs")?;
args.get(offset..end)
.ok_or("invalid_operator_source_pairs")
args.get(offset..end).ok_or("invalid_operator_source_pairs")
}
@@ -0,0 +1,138 @@
//! Choose and start the engine: the Original serve path, or one of the experimental owners.
use super::*;
use leleka_backend_api::{Backend, BackendError};
use leleka_runtime::backend::EvaluationObserver;
type Spawned = Result<Box<dyn Backend>, BackendError>;
type OwnerSpawn = fn(NativeBackendConfig, RankedExpertProfileSource) -> Spawned;
const ADAPTIVE_SLOTS_PROFILE_FAULT: &str = "adaptive_slots_requires_ranked_expert_profile";
/// Resolve the serve mode and start the engine; the transport stays closed for model admission.
pub(super) fn start_backend(operator: Operator) -> Result<Box<dyn Backend>, Failure> {
let Operator {
config,
requested_mode,
mut original_options,
mut selection,
..
} = operator;
let observer = selection
.public_output
.take()
.map(evaluation_measurement::observer_adaptive_slots)
.transpose()?;
let mode = select_mode(requested_mode, &selection, observer.is_some())?;
original_options.mode = mode;
let choice = original_serve_choice(mode, &config).map_err(|error| {
// Fixed texts naming the missing assets or unsupported configuration; never operator paths.
eprintln!("leleka-inference: {}", error.message);
"original_serve_unavailable"
})?;
announce_preview(&choice, mode);
spawn_choice(choice, config, original_options, selection, observer)?.map_err(|error| {
eprintln!("leleka-inference: {}", error.message);
"runtime_startup_failed".into()
})
}
fn announce_preview(choice: &OriginalServeChoice, mode: OriginalServeMode) {
if let OriginalServeChoice::Preview { reason } = choice
&& mode == OriginalServeMode::Auto
{
eprintln!("leleka-inference: backend=preview ({reason})");
}
}
/// The outer error is a missing ranked profile; the inner one is the engine's own start-up failure.
fn spawn_choice(
choice: OriginalServeChoice,
config: NativeBackendConfig,
original_options: OriginalServeOptions,
selection: Selection,
observer: Option<EvaluationObserver>,
) -> Result<Spawned, &'static str> {
if matches!(choice, OriginalServeChoice::Original) {
return Ok(spawn::<Qwen35Cuda>(Qwen35CudaStart::OriginalServe(
config,
original_options,
)));
}
if let Some(observer) = observer {
let profile = selection
.ranked_profile
.ok_or(ADAPTIVE_SLOTS_PROFILE_FAULT)?;
return Ok(
spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots(
config, profile, observer,
),
);
}
if let Some((spawn_owner, fault)) = owner_spawner(&selection) {
return Ok(spawn_owner(config, selection.ranked_profile.ok_or(fault)?));
}
Ok(spawn_plain(config, selection))
}
/// The owner variant the selection names, with the error text for its missing ranked profile.
fn owner_spawner(selection: &Selection) -> Option<(OwnerSpawn, &'static str)> {
adaptive_resident_scratch_spawner(selection).or_else(|| spill_queued_spawner(selection))
}
fn adaptive_resident_scratch_spawner(selection: &Selection) -> Option<(OwnerSpawn, &'static str)> {
let owners: [(bool, OwnerSpawn, &'static str); 3] = [
(
selection.adaptive_slots,
spawn_backend_experimental_optimized_windowed256_adaptive_slots,
ADAPTIVE_SLOTS_PROFILE_FAULT,
),
(
selection.resident_owners,
spawn_backend_experimental_optimized_windowed256_resident_owners,
"resident_owners_requires_ranked_expert_profile",
),
(
selection.retained_scratch,
spawn_backend_experimental_optimized_windowed256_retained_scratch,
"retained_scratch_requires_ranked_expert_profile",
),
];
first_selected(owners)
}
fn spill_queued_spawner(selection: &Selection) -> Option<(OwnerSpawn, &'static str)> {
let owners: [(bool, OwnerSpawn, &'static str); 2] = [
(
selection.streamed_spill,
spawn_backend_experimental_optimized_windowed256_streamed_spill,
"streamed_spill_requires_ranked_expert_profile",
),
(
selection.queued_owners,
spawn_backend_experimental_optimized_windowed256_queued_owners,
"queued_owners_require_ranked_expert_profile",
),
];
first_selected(owners)
}
fn first_selected<const N: usize>(
owners: [(bool, OwnerSpawn, &'static str); N],
) -> Option<(OwnerSpawn, &'static str)> {
owners
.into_iter()
.find(|(selected, ..)| *selected)
.map(|(_, spawn_owner, fault)| (spawn_owner, fault))
}
/// The optimized, the integer-windowed or the native engine.
fn spawn_plain(config: NativeBackendConfig, selection: Selection) -> Spawned {
if selection.optimized {
spawn_backend_experimental_optimized_windowed256(config, selection.ranked_profile)
} else if selection.integer_windowed {
spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr(config)
} else {
spawn::<Qwen35Cuda>(Qwen35CudaStart::Native(config))
}
}
@@ -20,28 +20,12 @@ pub(super) fn operator_public_evaluation_output(
.ok_or("public_evaluation_output_required")?;
output = Some(PathBuf::from(path));
offset += 2;
} else if [
ADAPTIVE_SLOTS_FLAG,
RESIDENT_OWNERS_FLAG,
RETAINED_SCRATCH_FLAG,
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
]
.contains(&args[offset].as_str())
{
} else if EXECUTION_FLAGS.contains(&args[offset].as_str()) {
ordinary.push(args[offset].clone());
offset += 1;
} else {
let end = offset
.checked_add(4)
.ok_or("invalid_operator_source_pairs")?;
ordinary.extend_from_slice(
args.get(offset..end)
.ok_or("invalid_operator_source_pairs")?,
);
offset = end;
ordinary.extend_from_slice(source_tuple(args, offset)?);
offset += 4;
}
}
Ok((output, ordinary))
@@ -37,31 +37,8 @@ pub(super) fn operator_optimized_execution(
ordinary.push(args[offset].clone());
offset += 1;
} else {
let end = offset
.checked_add(4)
.ok_or("invalid_operator_source_pairs")?;
let tuple = args
.get(offset..end)
.ok_or("invalid_operator_source_pairs")?;
if tuple[0] == "--ranked-expert-profile" {
if profile.is_some()
|| tuple[1].is_empty()
|| tuple[2] != "--expert-profile-sha256"
|| tuple[3].len() != 64
|| !tuple[3]
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err("invalid_ranked_expert_profile_arguments");
}
profile = Some(RankedExpertProfileSource {
path: tuple[1].clone().into(),
sha256: tuple[3].clone(),
});
} else {
ordinary.extend_from_slice(tuple);
}
offset = end;
take_profile_tuple(source_tuple(args, offset)?, &mut profile, &mut ordinary)?;
offset += 4;
}
}
if profile.is_some() && !selected {
@@ -70,7 +47,42 @@ pub(super) fn operator_optimized_execution(
Ok((selected, profile, ordinary))
}
/// A standalone opt-in is parsed only at a source-tuple boundary. Artifact
/// One source tuple: the ranked expert profile, or an ordinary tuple kept for the later parsers.
fn take_profile_tuple(
tuple: &[String],
profile: &mut Option<RankedExpertProfileSource>,
ordinary: &mut Vec<String>,
) -> Result<(), &'static str> {
if tuple[0] == "--ranked-expert-profile" {
*profile = Some(ranked_profile(tuple, profile.is_some())?);
} else {
ordinary.extend_from_slice(tuple);
}
Ok(())
}
/// `--ranked-expert-profile PATH --expert-profile-sha256 HEX64`, given once.
fn ranked_profile(
tuple: &[String],
taken: bool,
) -> Result<RankedExpertProfileSource, &'static str> {
if taken
|| tuple[1].is_empty()
|| tuple[2] != "--expert-profile-sha256"
|| tuple[3].len() != 64
|| !tuple[3]
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err("invalid_ranked_expert_profile_arguments");
}
Ok(RankedExpertProfileSource {
path: tuple[1].clone().into(),
sha256: tuple[3].clone(),
})
}
// A standalone opt-in is parsed only at a source-tuple boundary. Artifact
/// operands remain opaque and are never scanned or interpreted as switches.
pub(super) fn operator_execution(args: &[String]) -> Result<(bool, Vec<String>), &'static str> {
let mut selected = false;
@@ -101,19 +113,22 @@ pub(super) fn operator_execution(args: &[String]) -> Result<(bool, Vec<String>),
mod queued_owner_operator_tests {
use super::*;
#[test]
fn queued_owner_selection_requires_profile_and_refuses_conflicts_without_scanning_operands() {
let profile = [
fn profile_tuple() -> [String; 4] {
[
"--ranked-expert-profile",
"sanitized-profile",
"--expert-profile-sha256",
"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf",
]
.map(String::from);
let mtp = ["--mtp-pack", QUEUED_OWNERS_FLAG, "--mtp-staging", "private"].map(String::from);
let (selected, ordinary) = operator_queued_owners_execution(&mtp).unwrap();
assert!(!selected);
assert_eq!(ordinary, mtp);
.map(String::from)
}
fn mtp_with_marker() -> [String; 4] {
["--mtp-pack", QUEUED_OWNERS_FLAG, "--mtp-staging", "private"].map(String::from)
}
/// The flag in front of, or behind, the profile and the pack routes to the optimized parser.
fn assert_selection_feeds_the_optimized_parser(profile: &[String; 4], mtp: &[String; 4]) {
for args in [
[QUEUED_OWNERS_FLAG.to_owned()]
.into_iter()
@@ -132,14 +147,20 @@ mod queued_owner_operator_tests {
let (optimized, profile, ordinary) = operator_optimized_execution(&parsed).unwrap();
assert!(optimized);
assert_eq!(profile.unwrap().path, PathBuf::from("sanitized-profile"));
assert_eq!(ordinary, mtp);
assert_eq!(ordinary, *mtp);
}
}
fn assert_other_execution_flags_conflict() {
for other in [QUEUED_OWNERS_FLAG, OPTIMIZED_FLAG, INTEGER_WINDOWED_FLAG] {
assert!(
operator_queued_owners_execution(&[QUEUED_OWNERS_FLAG.into(), other.into()])
.is_err()
);
}
}
fn assert_empty_unknown_and_duplicate_profiles() {
let (_, empty) = operator_queued_owners_execution(&[QUEUED_OWNERS_FLAG.into()]).unwrap();
let (_, profile, _) = operator_optimized_execution(&empty).unwrap();
assert!(profile.is_none()); // main refuses this before spawning the owner.
@@ -154,75 +175,90 @@ mod queued_owner_operator_tests {
assert!(operator_optimized_execution(&parsed).is_err());
}
fn profile_tuple() -> [String; 4] {
[
"--ranked-expert-profile",
"sanitized-profile",
"--expert-profile-sha256",
"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf",
]
.map(String::from)
#[test]
fn queued_owner_selection_requires_profile_and_refuses_conflicts_without_scanning_operands() {
let profile = profile_tuple();
let mtp = mtp_with_marker();
let (selected, ordinary) = operator_queued_owners_execution(&mtp).unwrap();
assert!(!selected);
assert_eq!(ordinary, mtp);
assert_selection_feeds_the_optimized_parser(&profile, &mtp);
assert_other_execution_flags_conflict();
assert_empty_unknown_and_duplicate_profiles();
}
}
#[cfg(test)]
mod optimized_operator_tests {
use super::*;
#[test]
fn optimized_profile_is_closed_at_tuple_boundaries_and_does_not_select_old_sources() {
let sha = "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf";
let tuple = [
const SHA: &str = "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf";
fn tuple() -> [String; 4] {
[
"--ranked-expert-profile",
"synthetic-profile",
"--expert-profile-sha256",
sha,
SHA,
]
.map(String::from);
let mtp = ["--mtp-pack", OPTIMIZED_FLAG, "--mtp-staging", "private"].map(String::from);
let (selected, profile, ordinary) = operator_optimized_execution(&mtp).unwrap();
assert!(!selected);
assert!(profile.is_none());
assert_eq!(ordinary, mtp);
assert!(operator_optimized_execution(&tuple).is_err());
let args = [String::from(OPTIMIZED_FLAG)]
.into_iter()
.chain(tuple.clone())
.chain(mtp.clone())
.collect::<Vec<_>>();
.map(String::from)
}
fn mtp_with_marker() -> [String; 4] {
["--mtp-pack", OPTIMIZED_FLAG, "--mtp-staging", "private"].map(String::from)
}
fn with_flag(flag: &str, rest: impl IntoIterator<Item = String>) -> Vec<String> {
[String::from(flag)].into_iter().chain(rest).collect()
}
fn assert_selected_profile_and_duplicates(tuple: &[String; 4], mtp: &[String; 4]) {
let args = with_flag(OPTIMIZED_FLAG, tuple.clone().into_iter().chain(mtp.clone()));
let (selected, profile, ordinary) = operator_optimized_execution(&args).unwrap();
assert!(selected);
let profile = profile.unwrap();
assert_eq!(profile.path, PathBuf::from("synthetic-profile"));
assert_eq!(profile.sha256, sha);
assert_eq!(ordinary, mtp);
assert_eq!(profile.sha256, SHA);
assert_eq!(ordinary, *mtp);
assert!(
operator_optimized_execution(&[OPTIMIZED_FLAG.into(), OPTIMIZED_FLAG.into()]).is_err()
);
let duplicate = args.iter().chain(&tuple).cloned().collect::<Vec<_>>();
let duplicate = args.iter().chain(tuple).cloned().collect::<Vec<_>>();
assert!(operator_optimized_execution(&duplicate).is_err());
}
fn assert_incomplete_and_wrong_digests_refused(tuple: &[String; 4]) {
for length in 1..4 {
let incomplete = [String::from(OPTIMIZED_FLAG)]
.into_iter()
.chain(tuple[..length].iter().cloned())
.collect::<Vec<_>>();
let incomplete = with_flag(OPTIMIZED_FLAG, tuple[..length].iter().cloned());
assert!(operator_optimized_execution(&incomplete).is_err());
}
for wrong_sha in ["", "G", "0123", &"F".repeat(64)] {
let mut bad = tuple.clone();
bad[3] = wrong_sha.into();
let invalid = [String::from(OPTIMIZED_FLAG)]
.into_iter()
.chain(bad)
.collect::<Vec<_>>();
let invalid = with_flag(OPTIMIZED_FLAG, bad);
assert!(operator_optimized_execution(&invalid).is_err());
}
let old = [String::from(INTEGER_WINDOWED_FLAG)]
.into_iter()
.chain(mtp.clone())
.collect::<Vec<_>>();
}
fn assert_old_flag_is_left_alone(mtp: &[String; 4]) {
let old = with_flag(INTEGER_WINDOWED_FLAG, mtp.clone());
let (optimized, profile, ordinary) = operator_optimized_execution(&old).unwrap();
assert!(!optimized);
assert!(profile.is_none());
assert_eq!(operator_execution(&ordinary).unwrap(), (true, mtp.to_vec()));
}
#[test]
fn optimized_profile_is_closed_at_tuple_boundaries_and_does_not_select_old_sources() {
let tuple = tuple();
let mtp = mtp_with_marker();
let (selected, profile, ordinary) = operator_optimized_execution(&mtp).unwrap();
assert!(!selected);
assert!(profile.is_none());
assert_eq!(ordinary, mtp);
assert!(operator_optimized_execution(&tuple).is_err());
assert_selected_profile_and_duplicates(&tuple, &mtp);
assert_incomplete_and_wrong_digests_refused(&tuple);
assert_old_flag_is_left_alone(&mtp);
}
}
@@ -0,0 +1,37 @@
//! The `--help` text.
pub(super) const HELP: &str = concat!(
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ",
"ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | ",
"--kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH ",
"(read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned ",
"archive)] [--mtp-pack PATH --mtp-staging PATH] ",
"[--experimental-native-integer-iq3-windowed256-retained-gr | ",
"--experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH ",
"--expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners ",
"--ranked-expert-profile PATH --expert-profile-sha256 DIGEST | ",
"--experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH ",
"--expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch ",
"--ranked-expert-profile PATH --expert-profile-sha256 DIGEST | ",
"--experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH ",
"--expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl ",
"(adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] ",
"[--backend-mode auto|original|preview (default auto; an --experimental-* flag selects ",
"preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir ",
"PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS ",
"(default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, ",
"default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] ",
"[--turn-token ID (negative = none)] [--prefix-cache-mib auto|N|0 (cross-session prefix ",
"cache in host RAM, replaces the conversation cache; auto = a share of the memory available ",
"at start; default off)] [--prefix-cache-tail off|prompt|reply (also checkpoint where the ",
"next turn resumes: the end of the prompt, or of the reply too (experimental); default off)] ",
"[--prefix-cache-block TOKENS (block and chunk-grid size, a multiple of 256; default the ",
"prefill capacity)] [--verify-only (verify shards and archive, print timings, exit)] ",
"[--kar-sparse-extents-sha256 HEX (with --kar-archive-fd: the sealed memfd holds only the ",
"byte ranges the serve path reads and is verified against the pinned SHA-256 of those ranges ",
"instead of the archive's)] [--kar-attested-by-stamp (the parent verified the archive file's ",
"stamp; the sealed memfd is not hashed again)] [--verify-stamps DIR [--verify-rehash] (skip ",
"the hash of a file that is unchanged since it last matched its pin)] [--expert-source ",
"resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: ",
"read-only mappings of shard 0, the low-RAM laptop form)]",
);
+33 -200
View File
@@ -15,6 +15,16 @@ mod adaptive_slots;
use adaptive_slots::*;
mod original_serve;
use original_serve::*;
mod original_serve_parser;
use original_serve_parser::*;
mod backend_choice;
use backend_choice::*;
mod help;
use help::HELP;
mod selection;
use selection::*;
mod startup;
use startup::*;
mod evaluation_output;
use evaluation_output::*;
@@ -69,214 +79,37 @@ const EXECUTION_FLAGS: [&str; 7] = [
INTEGER_WINDOWED_FLAG,
];
type Failure = Box<dyn std::error::Error>;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn main() -> Result<(), Failure> {
let mut args: Vec<String> = std::env::args().skip(1).collect();
// `--verify-only`: run the load-time source verification (shards, KAR archive) and exit; no CUDA is touched.
let verify_only = args.iter().any(|arg| arg == "--verify-only");
args.retain(|arg| arg != "--verify-only");
// `--verify-stamps DIR [--verify-rehash]`: a file that already matched its pinned digest and is unchanged
// (device, inode, size, mtime, ctime) is not hashed again; `--verify-rehash` hashes everything and renews
// the stamps. Without `--verify-stamps` every start verifies in full.
let verify_rehash = args.iter().any(|arg| arg == "--verify-rehash");
args.retain(|arg| arg != "--verify-rehash");
if args.iter().any(|arg| arg == "--kar-attested-by-stamp") {
// Only `leleka run` passes this, after matching the stamp of the archive file it copied the memfd from.
args.retain(|arg| arg != "--kar-attested-by-stamp");
set_archive_attested();
}
// `--kar-sparse-extents-sha256 HEX` (only `leleka run` passes it, `memfd_extents: ple_only`, the form of rtx5090-32g): the sealed memfd holds
// only the byte ranges the serve path reads, and is verified against the pinned digest of those ranges.
let sparse_extents = take_option(&mut args, "--kar-sparse-extents-sha256")?
.map(|text| parse_sha256(&text))
.transpose()?;
let verify_stamps = take_option(&mut args, "--verify-stamps")?;
if let Some(directory) = verify_stamps {
if directory.is_empty() {
return Err("invalid_verify_stamps".into());
}
set_verify_stamps(PathBuf::from(directory), verify_rehash);
} else if verify_rehash {
return Err("verify_rehash_requires_verify_stamps".into());
}
let (verify_only, sparse_extents) = take_verification_flags(&mut args)?;
if args.as_slice() == ["--help"] {
println!(
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--prefix-cache-mib auto|N|0 (cross-session prefix cache in host RAM, replaces the conversation cache; auto = a share of the memory available at start; default off)] [--prefix-cache-tail off|prompt|reply (also checkpoint where the next turn resumes: the end of the prompt, or of the reply too (experimental); default off)] [--prefix-cache-block TOKENS (block and chunk-grid size, a multiple of 256; default the prefill capacity)] [--verify-only (verify shards and archive, print timings, exit)] [--kar-sparse-extents-sha256 HEX (with --kar-archive-fd: the sealed memfd holds only the byte ranges the serve path reads and is verified against the pinned SHA-256 of those ranges instead of the archive's)] [--kar-attested-by-stamp (the parent verified the archive file's stamp; the sealed memfd is not hashed again)] [--verify-stamps DIR [--verify-rehash] (skip the hash of a file that is unchanged since it last matched its pin)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]"
);
println!("{HELP}");
return Ok(());
}
let (base, extra) = if args.len() >= 14 {
args.split_at(14)
} else {
return Err("invalid_inference_arguments".into());
};
let (requested_mode, mut original_options, extra) = operator_original_serve(extra)?;
let (public_evaluation_output, execution_args) = operator_public_evaluation_output(&extra)?;
let (adaptive_slots, adaptive_args) = operator_adaptive_slots_execution(&execution_args)?;
if public_evaluation_output.is_some() && !adaptive_slots {
return Err("public_evaluation_requires_adaptive_slots".into());
}
let (resident_owners, resident_args) = operator_resident_owners_execution(&adaptive_args)?;
let (retained_scratch, scratch_args) = operator_retained_scratch_execution(&resident_args)?;
let (streamed_spill, streamed_args) = operator_streamed_spill_execution(&scratch_args)?;
let (queued_owners, optimized_args) = operator_queued_owners_execution(&streamed_args)?;
let (optimized, ranked_profile, ordinary) = operator_optimized_execution(&optimized_args)?;
let (experimental_integer_windowed, source_args) = operator_execution(&ordinary)?;
if optimized && experimental_integer_windowed {
return Err("conflicting_experimental_execution_flags".into());
}
let sources = operator_sources_with_inherited(&source_args)?;
let [
l,
address,
t,
token_env,
s0,
shard0,
s1,
shard1,
g,
gpu,
b,
budget,
c,
context,
] = base
else {
return Err("invalid_inference_arguments".into());
};
if l != "--listen"
|| t != "--token-env"
|| s0 != "--shard0"
|| s1 != "--shard1"
|| g != "--gpu"
|| b != "--gpu-budget"
|| c != "--context-tokens"
{
return Err("invalid_inference_arguments".into());
}
let address: SocketAddr = address.parse().map_err(|_| "invalid_runtime_endpoint")?;
if !address.ip().is_loopback() {
return Err("loopback_required".into());
}
if token_env.is_empty()
|| !token_env
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
{
return Err("invalid_token_environment_name".into());
}
let token = std::env::var(token_env).map_err(|_| "missing_runtime_credential")?;
if !(32..=4096).contains(&token.len()) || !token.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
return Err("invalid_runtime_credential".into());
}
let config = NativeBackendConfig {
shard0: PathBuf::from(shard0),
shard1: PathBuf::from(shard1),
gpu_device_ordinal: gpu.parse().map_err(|_| "invalid_gpu_ordinal")?,
gpu_budget_bytes: budget.parse().map_err(|_| "invalid_gpu_budget")?,
context_tokens: context.parse().map_err(|_| "invalid_context_bound")?,
kar_ple_source: sources.kar,
kar_ple_inherited: match (sources.inherited, sources.kar_file) {
(Some((fd, provenance)), None) => Some(match sparse_extents {
Some(digest) => InheritedKarArchive::open_sparse(fd, provenance, digest)?,
None => InheritedKarArchive::open(fd, provenance)?,
}),
// Low-RAM form (docs/laptop-profile.md): an ordinary read-only file instead of a 55 GB sealed memfd.
(None, Some((file, provenance))) if sparse_extents.is_none() => {
Some(InheritedKarArchive::open_read_only_file(&file, provenance)?)
}
_ if sparse_extents.is_some() => {
return Err("kar_sparse_extents_requires_kar_archive_fd".into());
}
_ => None,
},
mtp_source: sources.mtp,
// The routed-expert KAR source has no operator flag in this binary yet.
kar_expert_source: None,
experimental: Default::default(),
};
let operator = parse_operator(&args, sparse_extents)?;
if verify_only {
return verify_sources_only(config).map_err(|error| {
eprintln!("leleka-inference: {}", error.message);
"source_verification_failed".into()
});
return verify_sources(operator.config);
}
let observer = public_evaluation_output
.map(evaluation_measurement::observer_adaptive_slots)
.transpose()?;
// An explicit experimental execution flag is an explicit preview choice unless the mode is also given.
let explicit_preview = adaptive_slots
|| resident_owners
|| retained_scratch
|| streamed_spill
|| queued_owners
|| optimized
|| experimental_integer_windowed;
let mode = match requested_mode {
Some(mode) => mode,
None if explicit_preview => OriginalServeMode::Preview,
None => OriginalServeMode::Auto,
};
if mode == OriginalServeMode::Original && (explicit_preview || observer.is_some()) {
return Err("conflicting_experimental_execution_flags".into());
}
original_options.mode = mode;
let choice = original_serve_choice(mode, &config).map_err(|error| {
// Fixed texts naming the missing assets or unsupported configuration; never operator paths.
let (address, token) = (operator.address, operator.token.clone());
serve(start_backend(operator)?, token, address).await
}
fn verify_sources(config: NativeBackendConfig) -> Result<(), Failure> {
verify_sources_only(config).map_err(|error| {
eprintln!("leleka-inference: {}", error.message);
"original_serve_unavailable"
})?;
if let OriginalServeChoice::Preview { reason } = &choice
&& mode == OriginalServeMode::Auto
{
eprintln!("leleka-inference: backend=preview ({reason})");
}
let backend = if matches!(choice, OriginalServeChoice::Original) {
spawn::<Qwen35Cuda>(Qwen35CudaStart::OriginalServe(config, original_options))
} else if let Some(observer) = observer {
spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots(
config,
ranked_profile.ok_or("adaptive_slots_requires_ranked_expert_profile")?,
observer,
)
} else if adaptive_slots {
spawn_backend_experimental_optimized_windowed256_adaptive_slots(
config,
ranked_profile.ok_or("adaptive_slots_requires_ranked_expert_profile")?,
)
} else if resident_owners {
spawn_backend_experimental_optimized_windowed256_resident_owners(
config,
ranked_profile.ok_or("resident_owners_requires_ranked_expert_profile")?,
)
} else if retained_scratch {
spawn_backend_experimental_optimized_windowed256_retained_scratch(
config,
ranked_profile.ok_or("retained_scratch_requires_ranked_expert_profile")?,
)
} else if streamed_spill {
spawn_backend_experimental_optimized_windowed256_streamed_spill(
config,
ranked_profile.ok_or("streamed_spill_requires_ranked_expert_profile")?,
)
} else if queued_owners {
spawn_backend_experimental_optimized_windowed256_queued_owners(
config,
ranked_profile.ok_or("queued_owners_require_ranked_expert_profile")?,
)
} else if optimized {
spawn_backend_experimental_optimized_windowed256(config, ranked_profile)
} else if experimental_integer_windowed {
spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr(config)
} else {
spawn::<Qwen35Cuda>(Qwen35CudaStart::Native(config))
}
.map_err(|error| {
eprintln!("leleka-inference: {}", error.message);
"runtime_startup_failed"
})?;
let server = RuntimeServer::new(backend, token.clone())?;
"source_verification_failed".into()
})
}
async fn serve(
backend: Box<dyn leleka_backend_api::Backend>,
token: String,
address: SocketAddr,
) -> Result<(), Failure> {
let server = RuntimeServer::new(backend, token)?;
let listener = tokio::net::TcpListener::bind(address).await?;
// Transport starts closed for model admission. Loading is an explicit typed
// lifecycle command; successful configuration parsing is never model ready.
@@ -2,164 +2,20 @@
use super::*;
pub(super) type Fault = &'static str;
/// The Original-serve options. Consumed first, at tuple boundaries only: the known one-item execution
/// flags and the fixture output pair are skipped as the later parsers read them, every other group is an
/// opaque four-item source tuple, so no operand is ever scanned for a flag.
pub(super) fn operator_original_serve(
args: &[String],
) -> Result<(Option<OriginalServeMode>, OriginalServeOptions, Vec<String>), &'static str> {
let mut mode = None;
let mut options = OriginalServeOptions::default();
let (mut capacity, mut directory, mut floor) = (false, false, false);
let (mut kv, mut kv_resident) = (false, false);
let (mut cache, mut every, mut root, mut turn) = (false, false, false, false);
let mut expert_source = false;
let (mut prefix_mib, mut prefix_block, mut prefix_tail) = (false, false, false);
let mut ordinary = Vec::with_capacity(args.len());
) -> Result<(Option<OriginalServeMode>, OriginalServeOptions, Vec<String>), Fault> {
let mut parser = OriginalServeParser::new(args.len());
let mut offset = 0usize;
while offset < args.len() {
let flag = args[offset].as_str();
let value = || {
args.get(offset + 1)
.map(String::as_str)
.ok_or("original_serve_option_value_required")
};
if flag == BACKEND_MODE_FLAG {
if mode.is_some() {
return Err("duplicate_backend_mode");
}
mode = Some(OriginalServeMode::parse(value()?).ok_or("invalid_backend_mode")?);
offset += 2;
} else if flag == ORIGINAL_PREFILL_CAPACITY_FLAG {
if std::mem::replace(&mut capacity, true) {
return Err("duplicate_original_prefill_capacity");
}
options.prefill_capacity = Some(
value()?
.parse()
.map_err(|_| "invalid_original_prefill_capacity")?,
);
offset += 2;
} else if flag == MTP_RT_DIR_FLAG {
if std::mem::replace(&mut directory, true) {
return Err("duplicate_mtp_rt_dir");
}
options.mtp_rt_directory = Some(PathBuf::from(value()?));
offset += 2;
} else if flag == SPEC_MIN_P_FLAG {
if std::mem::replace(&mut floor, true) {
return Err("duplicate_spec_min_p");
}
options.spec_min_p = value()?.parse().map_err(|_| "invalid_spec_min_p")?;
offset += 2;
} else if flag == KV_FLAG {
if std::mem::replace(&mut kv, true) {
return Err("duplicate_kv");
}
options.kv_format = Some(
leleka_runtime::memory_plan::KvFormat::parse_cli(value()?).ok_or("invalid_kv")?,
);
offset += 2;
} else if flag == KV_RESIDENT_FLAG {
if std::mem::replace(&mut kv_resident, true) {
return Err("duplicate_kv_resident");
}
options.kv_resident = Some(value()?.parse().map_err(|_| "invalid_kv_resident")?);
offset += 2;
} else if flag == PROMPT_CACHE_FLAG {
if std::mem::replace(&mut cache, true) {
return Err("duplicate_prompt_cache");
}
options.prompt_cache = value()?.parse().map_err(|_| "invalid_prompt_cache")?;
offset += 2;
} else if flag == PROMPT_CACHE_EVERY_FLAG {
if std::mem::replace(&mut every, true) {
return Err("duplicate_prompt_cache_every");
}
options.prompt_cache_every =
value()?.parse().map_err(|_| "invalid_prompt_cache_every")?;
offset += 2;
} else if flag == PROMPT_CACHE_ROOT_FLAG {
if std::mem::replace(&mut root, true) {
return Err("duplicate_prompt_cache_root");
}
options.prompt_cache_root =
value()?.parse().map_err(|_| "invalid_prompt_cache_root")?;
offset += 2;
} else if flag == TURN_TOKEN_FLAG {
if std::mem::replace(&mut turn, true) {
return Err("duplicate_turn_token");
}
let id: i64 = value()?.parse().map_err(|_| "invalid_turn_token")?;
options.turn_token = if id < 0 {
None
} else {
Some(u32::try_from(id).map_err(|_| "invalid_turn_token")?)
};
offset += 2;
} else if flag == PREFIX_CACHE_MIB_FLAG {
if std::mem::replace(&mut prefix_mib, true) {
return Err("duplicate_prefix_cache_mib");
}
let budget = leleka_runtime::prefix_cache::budget::parse_mib(value()?)?;
options
.prefix_cache
.get_or_insert_with(Default::default)
.budget_bytes = budget;
offset += 2;
} else if flag == PREFIX_CACHE_TAIL_FLAG {
if std::mem::replace(&mut prefix_tail, true) {
return Err("duplicate_prefix_cache_tail");
}
options
.prefix_cache
.get_or_insert_with(Default::default)
.tail = leleka_runtime::backend::PrefixTail::parse(value()?)
.ok_or("invalid_prefix_cache_tail")?;
offset += 2;
} else if flag == PREFIX_CACHE_BLOCK_FLAG {
if std::mem::replace(&mut prefix_block, true) {
return Err("duplicate_prefix_cache_block");
}
options
.prefix_cache
.get_or_insert_with(Default::default)
.block_tokens = value()?.parse().map_err(|_| "invalid_prefix_cache_block")?;
offset += 2;
} else if flag == EXPERT_SOURCE_FLAG {
if std::mem::replace(&mut expert_source, true) {
return Err("duplicate_expert_source");
}
options.expert_source = leleka_runtime::backend::ExpertSource::parse(value()?)
.ok_or("invalid_expert_source")?;
offset += 2;
} else if flag == PUBLIC_EVALUATION_OUTPUT_FLAG {
let end = offset
.checked_add(2)
.ok_or("public_evaluation_output_required")?;
ordinary.extend_from_slice(
args.get(offset..end)
.ok_or("public_evaluation_output_required")?,
);
offset = end;
} else if EXECUTION_FLAGS.contains(&flag) {
ordinary.push(args[offset].clone());
offset += 1;
} else {
let end = offset
.checked_add(4)
.ok_or("invalid_operator_source_pairs")?;
ordinary.extend_from_slice(
args.get(offset..end)
.ok_or("invalid_operator_source_pairs")?,
);
offset = end;
}
offset = parser.consume(args, offset)?;
}
if let Some(mode) = mode {
options.mode = mode;
}
Ok((mode, options, ordinary))
Ok(parser.finish())
}
#[cfg(test)]
@@ -169,53 +25,19 @@ mod original_serve_operator_tests {
items.iter().map(|s| s.to_string()).collect()
}
#[test]
fn expert_source_is_resident_by_default_and_mapped_on_request() {
let (_, options, rest) = operator_original_serve(&args(&[])).unwrap();
// Windows offers only the mapped form, so it is also the default there.
assert_eq!(
options.expert_source,
if cfg!(windows) {
leleka_runtime::backend::ExpertSource::Mapped
} else {
leleka_runtime::backend::ExpertSource::Resident
}
);
assert!(rest.is_empty());
let (_, options, rest) = operator_original_serve(&args(&[
fn mapped_source_flags() -> Vec<String> {
args(&[
"--expert-source",
"mapped",
"--kar-archive-file",
"/a.kar",
"--kar-provenance",
"/a.json",
]))
.unwrap();
assert_eq!(
options.expert_source,
leleka_runtime::backend::ExpertSource::Mapped
);
assert_eq!(
rest,
args(&[
"--kar-archive-file",
"/a.kar",
"--kar-provenance",
"/a.json"
])
);
for bad in [
args(&["--expert-source"]),
args(&["--expert-source", "copy"]),
args(&["--expert-source", "mapped", "--expert-source", "resident"]),
] {
assert!(operator_original_serve(&bad).is_err(), "{bad:?}");
}
])
}
#[test]
fn the_four_options_are_consumed_and_everything_else_passes_through_unchanged() {
let input = args(&[
fn consumed_options_input() -> Vec<String> {
args(&[
"--backend-mode",
"original",
"--original-prefill-capacity",
@@ -239,8 +61,64 @@ mod original_serve_operator_tests {
"/sanitized/s",
PUBLIC_EVALUATION_OUTPUT_FLAG,
"/sanitized/out",
]);
let (mode, options, rest) = operator_original_serve(&input).unwrap();
])
}
fn passed_through() -> Vec<String> {
args(&[
OPTIMIZED_FLAG,
"--kar-archive",
"/sanitized/a",
"--kar-staging",
"/sanitized/s",
PUBLIC_EVALUATION_OUTPUT_FLAG,
"/sanitized/out",
])
}
fn assert_bad_expert_sources_refused() {
for bad in [
args(&["--expert-source"]),
args(&["--expert-source", "copy"]),
args(&["--expert-source", "mapped", "--expert-source", "resident"]),
] {
assert!(operator_original_serve(&bad).is_err(), "{bad:?}");
}
}
#[test]
fn expert_source_is_resident_by_default_and_mapped_on_request() {
let (_, options, rest) = operator_original_serve(&args(&[])).unwrap();
// Windows offers only the mapped form, so it is also the default there.
assert_eq!(
options.expert_source,
if cfg!(windows) {
leleka_runtime::backend::ExpertSource::Mapped
} else {
leleka_runtime::backend::ExpertSource::Resident
}
);
assert!(rest.is_empty());
let (_, options, rest) = operator_original_serve(&mapped_source_flags()).unwrap();
assert_eq!(
options.expert_source,
leleka_runtime::backend::ExpertSource::Mapped
);
assert_eq!(
rest,
args(&[
"--kar-archive-file",
"/a.kar",
"--kar-provenance",
"/a.json"
])
);
assert_bad_expert_sources_refused();
}
#[test]
fn the_four_options_are_consumed_and_everything_else_passes_through_unchanged() {
let (mode, options, rest) = operator_original_serve(&consumed_options_input()).unwrap();
assert_eq!(mode, Some(OriginalServeMode::Original));
assert_eq!(options.mode, OriginalServeMode::Original);
assert_eq!(options.prefill_capacity, Some(1024));
@@ -258,18 +136,7 @@ mod original_serve_operator_tests {
),
(6, 4096, 1024, None)
);
assert_eq!(
rest,
args(&[
OPTIMIZED_FLAG,
"--kar-archive",
"/sanitized/a",
"--kar-staging",
"/sanitized/s",
PUBLIC_EVALUATION_OUTPUT_FLAG,
"/sanitized/out"
])
);
assert_eq!(rest, passed_through());
}
#[test]
@@ -0,0 +1,228 @@
//! The state of one pass over the Original-serve options.
use super::*;
type OptionValue<'a> = Result<&'a str, Fault>;
/// The state of one pass over the arguments: the parsed options, the flags already seen, the rest.
pub(super) struct OriginalServeParser {
mode: Option<OriginalServeMode>,
options: OriginalServeOptions,
seen: Vec<&'static str>,
ordinary: Vec<String>,
}
impl OriginalServeParser {
pub(super) fn new(capacity: usize) -> Self {
Self {
mode: None,
options: OriginalServeOptions::default(),
seen: Vec::new(),
ordinary: Vec::with_capacity(capacity),
}
}
/// Handle the group at `offset` and return where the next one starts.
pub(super) fn consume(&mut self, args: &[String], offset: usize) -> Result<usize, Fault> {
let flag = args[offset].as_str();
let value = args
.get(offset + 1)
.map(String::as_str)
.ok_or("original_serve_option_value_required");
if self.apply_option(flag, value)? {
return Ok(offset + 2);
}
if flag == PUBLIC_EVALUATION_OUTPUT_FLAG {
return self.pass_through(args, offset, 2, "public_evaluation_output_required");
}
if EXECUTION_FLAGS.contains(&flag) {
self.ordinary.push(args[offset].clone());
return Ok(offset + 1);
}
self.pass_through(args, offset, 4, "invalid_operator_source_pairs")
}
/// Keep `width` items from `offset` for the later parsers.
fn pass_through(
&mut self,
args: &[String],
offset: usize,
width: usize,
fault: Fault,
) -> Result<usize, Fault> {
let end = offset.checked_add(width).ok_or(fault)?;
self.ordinary
.extend_from_slice(args.get(offset..end).ok_or(fault)?);
Ok(end)
}
pub(super) fn finish(
mut self,
) -> (Option<OriginalServeMode>, OriginalServeOptions, Vec<String>) {
if let Some(mode) = self.mode {
self.options.mode = mode;
}
(self.mode, self.options, self.ordinary)
}
/// Whether `flag` is an Original-serve option (its value is applied); a repeat is refused.
fn apply_option(&mut self, flag: &str, value: OptionValue<'_>) -> Result<bool, Fault> {
Ok(self.apply_engine_option(flag, value)?
|| self.apply_cache_option(flag, value)?
|| self.apply_prefix_option(flag, value)?)
}
/// Refuse the second use of a flag.
fn first_use(&mut self, flag: &'static str, fault: Fault) -> Result<(), Fault> {
if self.seen.contains(&flag) {
return Err(fault);
}
self.seen.push(flag);
Ok(())
}
fn apply_engine_option(&mut self, flag: &str, value: OptionValue<'_>) -> Result<bool, Fault> {
let applied = match flag {
BACKEND_MODE_FLAG => self.backend_mode(value),
ORIGINAL_PREFILL_CAPACITY_FLAG => self.prefill_capacity(value),
MTP_RT_DIR_FLAG => self.mtp_directory(value),
SPEC_MIN_P_FLAG => self.spec_min_p(value),
KV_FLAG => self.kv_format(value),
KV_RESIDENT_FLAG => self.kv_resident(value),
EXPERT_SOURCE_FLAG => self.expert_source(value),
_ => return Ok(false),
};
applied.map(|()| true)
}
fn apply_cache_option(&mut self, flag: &str, value: OptionValue<'_>) -> Result<bool, Fault> {
let applied = match flag {
PROMPT_CACHE_FLAG => self.prompt_cache(value),
PROMPT_CACHE_EVERY_FLAG => self.prompt_cache_every(value),
PROMPT_CACHE_ROOT_FLAG => self.prompt_cache_root(value),
TURN_TOKEN_FLAG => self.turn_token(value),
_ => return Ok(false),
};
applied.map(|()| true)
}
fn apply_prefix_option(&mut self, flag: &str, value: OptionValue<'_>) -> Result<bool, Fault> {
let applied = match flag {
PREFIX_CACHE_MIB_FLAG => self.prefix_cache_budget(value),
PREFIX_CACHE_TAIL_FLAG => self.prefix_cache_tail(value),
PREFIX_CACHE_BLOCK_FLAG => self.prefix_cache_block(value),
_ => return Ok(false),
};
applied.map(|()| true)
}
fn backend_mode(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(BACKEND_MODE_FLAG, "duplicate_backend_mode")?;
self.mode = Some(OriginalServeMode::parse(value?).ok_or("invalid_backend_mode")?);
Ok(())
}
fn prefill_capacity(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
let flag = ORIGINAL_PREFILL_CAPACITY_FLAG;
self.first_use(flag, "duplicate_original_prefill_capacity")?;
let capacity = value?.parse();
self.options.prefill_capacity =
Some(capacity.map_err(|_| "invalid_original_prefill_capacity")?);
Ok(())
}
fn mtp_directory(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(MTP_RT_DIR_FLAG, "duplicate_mtp_rt_dir")?;
self.options.mtp_rt_directory = Some(PathBuf::from(value?));
Ok(())
}
fn spec_min_p(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(SPEC_MIN_P_FLAG, "duplicate_spec_min_p")?;
self.options.spec_min_p = value?.parse().map_err(|_| "invalid_spec_min_p")?;
Ok(())
}
fn kv_format(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(KV_FLAG, "duplicate_kv")?;
let format = leleka_runtime::memory_plan::KvFormat::parse_cli(value?);
self.options.kv_format = Some(format.ok_or("invalid_kv")?);
Ok(())
}
fn kv_resident(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(KV_RESIDENT_FLAG, "duplicate_kv_resident")?;
self.options.kv_resident = Some(value?.parse().map_err(|_| "invalid_kv_resident")?);
Ok(())
}
fn expert_source(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(EXPERT_SOURCE_FLAG, "duplicate_expert_source")?;
let source = leleka_runtime::backend::ExpertSource::parse(value?);
self.options.expert_source = source.ok_or("invalid_expert_source")?;
Ok(())
}
fn prompt_cache(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(PROMPT_CACHE_FLAG, "duplicate_prompt_cache")?;
self.options.prompt_cache = value?.parse().map_err(|_| "invalid_prompt_cache")?;
Ok(())
}
fn prompt_cache_every(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(PROMPT_CACHE_EVERY_FLAG, "duplicate_prompt_cache_every")?;
let every = value?.parse();
self.options.prompt_cache_every = every.map_err(|_| "invalid_prompt_cache_every")?;
Ok(())
}
fn prompt_cache_root(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(PROMPT_CACHE_ROOT_FLAG, "duplicate_prompt_cache_root")?;
let root = value?.parse();
self.options.prompt_cache_root = root.map_err(|_| "invalid_prompt_cache_root")?;
Ok(())
}
fn turn_token(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(TURN_TOKEN_FLAG, "duplicate_turn_token")?;
let id: i64 = value?.parse().map_err(|_| "invalid_turn_token")?;
self.options.turn_token = if id < 0 {
None
} else {
Some(u32::try_from(id).map_err(|_| "invalid_turn_token")?)
};
Ok(())
}
fn prefix_cache_budget(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(PREFIX_CACHE_MIB_FLAG, "duplicate_prefix_cache_mib")?;
let budget = leleka_runtime::prefix_cache::budget::parse_mib(value?)?;
let cache = self
.options
.prefix_cache
.get_or_insert_with(Default::default);
cache.budget_bytes = budget;
Ok(())
}
fn prefix_cache_tail(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(PREFIX_CACHE_TAIL_FLAG, "duplicate_prefix_cache_tail")?;
let tail = leleka_runtime::backend::PrefixTail::parse(value?);
let cache = self
.options
.prefix_cache
.get_or_insert_with(Default::default);
cache.tail = tail.ok_or("invalid_prefix_cache_tail")?;
Ok(())
}
fn prefix_cache_block(&mut self, value: OptionValue<'_>) -> Result<(), Fault> {
self.first_use(PREFIX_CACHE_BLOCK_FLAG, "duplicate_prefix_cache_block")?;
let cache = self
.options
.prefix_cache
.get_or_insert_with(Default::default);
cache.block_tokens = value?.parse().map_err(|_| "invalid_prefix_cache_block")?;
Ok(())
}
}
@@ -9,12 +9,12 @@ pub(super) fn operator_resident_owners_execution(
args,
RESIDENT_OWNERS_FLAG,
&[
RETAINED_SCRATCH_FLAG,
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
],
RETAINED_SCRATCH_FLAG,
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
],
"duplicate_retained_scratch_execution_flag",
RETAINED_SCRATCH_FLAG,
)
@@ -9,11 +9,11 @@ pub(super) fn operator_retained_scratch_execution(
args,
RETAINED_SCRATCH_FLAG,
&[
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
],
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
],
"duplicate_retained_scratch_execution_flag",
STREAMED_SPILL_FLAG,
)
@@ -22,6 +22,35 @@ pub(super) fn operator_retained_scratch_execution(
#[cfg(test)]
mod retained_scratch_operator_tests {
use super::*;
fn assert_mixed_modes_refused() {
for flag in [
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
RETAINED_SCRATCH_FLAG,
] {
assert!(
operator_retained_scratch_execution(&[RETAINED_SCRATCH_FLAG.into(), flag.into()])
.is_err()
);
}
}
fn assert_values_stay_opaque() {
let opaque = [
"--kar-archive",
RETAINED_SCRATCH_FLAG,
"--kar-staging",
"sanitized",
]
.map(String::from);
let (selected, unchanged) = operator_retained_scratch_execution(&opaque).unwrap();
assert!(!selected);
assert_eq!(unchanged, opaque);
}
#[test]
fn retained_scratch_selection_preserves_opaque_values_and_refuses_mixed_modes() {
let args = [
@@ -40,27 +69,7 @@ mod retained_scratch_operator_tests {
assert!(queued);
let (optimized, profile, rest) = operator_optimized_execution(&s).unwrap();
assert!(optimized && profile.is_some() && rest.is_empty());
for flag in [
STREAMED_SPILL_FLAG,
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
RETAINED_SCRATCH_FLAG,
] {
assert!(
operator_retained_scratch_execution(&[RETAINED_SCRATCH_FLAG.into(), flag.into()])
.is_err()
);
}
let opaque = [
"--kar-archive",
RETAINED_SCRATCH_FLAG,
"--kar-staging",
"sanitized",
]
.map(String::from);
let (selected, unchanged) = operator_retained_scratch_execution(&opaque).unwrap();
assert!(!selected);
assert_eq!(unchanged, opaque);
assert_mixed_modes_refused();
assert_values_stay_opaque();
}
}
@@ -0,0 +1,97 @@
//! Which execution the operator selected: the experimental flags, the public output and the ranked profile.
use super::*;
/// The execution flags found in the command line; at most one family may be selected.
pub(super) struct Selection {
pub(super) public_output: Option<PathBuf>,
pub(super) adaptive_slots: bool,
pub(super) resident_owners: bool,
pub(super) retained_scratch: bool,
pub(super) streamed_spill: bool,
pub(super) queued_owners: bool,
pub(super) optimized: bool,
pub(super) integer_windowed: bool,
pub(super) ranked_profile: Option<RankedExpertProfileSource>,
}
type FlagParser = fn(&[String]) -> Result<(bool, Vec<String>), &'static str>;
impl Selection {
/// An explicit experimental execution flag is an explicit preview choice unless the mode is also given.
fn explicit_preview(&self) -> bool {
self.adaptive_slots
|| self.resident_owners
|| self.retained_scratch
|| self.streamed_spill
|| self.queued_owners
|| self.optimized
|| self.integer_windowed
}
}
/// Consume one execution flag from `rest` and say whether it was given.
fn take_selection(rest: &mut Vec<String>, parse: FlagParser) -> Result<bool, &'static str> {
let (selected, remaining) = parse(rest)?;
*rest = remaining;
Ok(selected)
}
/// Read the execution flags of the `extra` arguments; the source arguments remain.
pub(super) fn select_execution(extra: &[String]) -> Result<(Selection, Vec<String>), Failure> {
let (mut selection, rest) = select_owner_flags(extra)?;
let source_args = select_optimized(&mut selection, &rest)?;
Ok((selection, source_args))
}
/// The public output pair and the adaptive-slots, resident, scratch, spill and queued-owner flags.
fn select_owner_flags(extra: &[String]) -> Result<(Selection, Vec<String>), Failure> {
let (public_output, mut rest) = operator_public_evaluation_output(extra)?;
let adaptive_slots = take_selection(&mut rest, operator_adaptive_slots_execution)?;
if public_output.is_some() && !adaptive_slots {
return Err("public_evaluation_requires_adaptive_slots".into());
}
let selection = Selection {
public_output,
adaptive_slots,
resident_owners: take_selection(&mut rest, operator_resident_owners_execution)?,
retained_scratch: take_selection(&mut rest, operator_retained_scratch_execution)?,
streamed_spill: take_selection(&mut rest, operator_streamed_spill_execution)?,
queued_owners: take_selection(&mut rest, operator_queued_owners_execution)?,
optimized: false,
integer_windowed: false,
ranked_profile: None,
};
Ok((selection, rest))
}
/// The optimized flag with its ranked profile and the old integer flag; returns the source arguments.
fn select_optimized(selection: &mut Selection, rest: &[String]) -> Result<Vec<String>, Failure> {
let (optimized, ranked_profile, ordinary) = operator_optimized_execution(rest)?;
let (integer_windowed, source_args) = operator_execution(&ordinary)?;
if optimized && integer_windowed {
return Err("conflicting_experimental_execution_flags".into());
}
selection.optimized = optimized;
selection.integer_windowed = integer_windowed;
selection.ranked_profile = ranked_profile;
Ok(source_args)
}
/// The serve mode: the requested one, else preview for an explicit experimental flag, else auto.
pub(super) fn select_mode(
requested: Option<OriginalServeMode>,
selection: &Selection,
observed: bool,
) -> Result<OriginalServeMode, &'static str> {
let explicit_preview = selection.explicit_preview();
let mode = match requested {
Some(mode) => mode,
None if explicit_preview => OriginalServeMode::Preview,
None => OriginalServeMode::Auto,
};
if mode == OriginalServeMode::Original && (explicit_preview || observed) {
return Err("conflicting_experimental_execution_flags");
}
Ok(mode)
}
+101 -91
View File
@@ -24,30 +24,9 @@ pub(super) fn operator_sources_with_inherited(
let mut ordinary = Vec::with_capacity(args.len());
for pair in args.as_chunks::<4>().0 {
if pair[0] == "--kar-archive-file" {
if kar_file.is_some()
|| pair[2] != "--kar-provenance"
|| pair[1].is_empty()
|| pair[3].is_empty()
{
return Err("invalid_kar_archive_file_arguments");
}
kar_file = Some((PathBuf::from(&pair[1]), PathBuf::from(&pair[3])));
kar_file = Some(kar_file_pair(pair, kar_file.is_some())?);
} else if pair[0] == "--kar-archive-fd" {
if inherited.is_some()
|| pair[2] != "--kar-provenance"
|| pair[1].is_empty()
|| !pair[1].bytes().all(|b| b.is_ascii_digit())
|| pair[3].is_empty()
{
return Err("invalid_inherited_kar_arguments");
}
let fd: u32 = pair[1]
.parse()
.map_err(|_| "invalid_inherited_kar_arguments")?;
if !(3..=1_048_576).contains(&fd) {
return Err("invalid_inherited_kar_arguments");
}
inherited = Some((fd, PathBuf::from(&pair[3])));
inherited = Some(inherited_pair(pair, inherited.is_some())?);
} else {
ordinary.extend_from_slice(pair);
}
@@ -64,6 +43,32 @@ pub(super) fn operator_sources_with_inherited(
})
}
/// `--kar-archive-file PATH --kar-provenance PATH`: both paths non-empty, given once.
fn kar_file_pair(pair: &[String; 4], taken: bool) -> Result<(PathBuf, PathBuf), &'static str> {
if taken || pair[2] != "--kar-provenance" || pair[1].is_empty() || pair[3].is_empty() {
return Err("invalid_kar_archive_file_arguments");
}
Ok((PathBuf::from(&pair[1]), PathBuf::from(&pair[3])))
}
/// `--kar-archive-fd N --kar-provenance PATH`: a descriptor in 3..=1048576 and the provenance path.
fn inherited_pair(pair: &[String; 4], taken: bool) -> Result<(u32, PathBuf), &'static str> {
const FAULT: &str = "invalid_inherited_kar_arguments";
if taken
|| pair[2] != "--kar-provenance"
|| pair[1].is_empty()
|| !pair[1].bytes().all(|b| b.is_ascii_digit())
|| pair[3].is_empty()
{
return Err(FAULT);
}
let fd: u32 = pair[1].parse().map_err(|_| FAULT)?;
if !(3..=1_048_576).contains(&fd) {
return Err(FAULT);
}
Ok((fd, PathBuf::from(&pair[3])))
}
pub(super) fn operator_sources(
args: &[String],
) -> Result<(OperatorSource, OperatorSource), &'static str> {
@@ -75,12 +80,7 @@ pub(super) fn operator_sources(
for pair in args.as_chunks::<4>().0 {
match pair[0].as_str() {
"--kar-archive" if kar.is_none() => kar = kar_source(pair)?,
"--mtp-pack"
if mtp.is_none()
&& pair[2] == "--mtp-staging"
&& !pair[1].is_empty()
&& !pair[3].is_empty() =>
{
"--mtp-pack" if mtp.is_none() && mtp_pair_is_closed(pair) => {
mtp = Some((PathBuf::from(&pair[1]), PathBuf::from(&pair[3])));
}
_ => return Err("invalid_operator_source_pairs"),
@@ -89,6 +89,11 @@ pub(super) fn operator_sources(
Ok((kar, mtp))
}
/// `--mtp-pack PATH --mtp-staging PATH` with both paths non-empty.
fn mtp_pair_is_closed(pair: &[String; 4]) -> bool {
pair[2] == "--mtp-staging" && !pair[1].is_empty() && !pair[3].is_empty()
}
pub(super) fn kar_source(args: &[String]) -> Result<Option<(PathBuf, PathBuf)>, &'static str> {
match args {
[] => Ok(None),
@@ -145,33 +150,79 @@ mod inherited_source_tests {
assert!(take_option(&mut missing, "--verify-stamps").is_err());
}
#[test]
fn read_only_file_form_is_exclusive_with_the_fd_and_the_staged_forms() {
let file = [
fn inherited_fd() -> [String; 4] {
["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from)
}
fn mtp_pair() -> [String; 4] {
["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from)
}
fn read_only_file() -> [String; 4] {
[
"--kar-archive-file",
"/assets/a.kar",
"--kar-provenance",
"/assets/a.json",
]
.map(String::from);
let mtp = ["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from);
let parsed =
operator_sources_with_inherited(&file.iter().chain(&mtp).cloned().collect::<Vec<_>>())
.unwrap();
.map(String::from)
}
fn joined(first: &[String], second: &[String]) -> Vec<String> {
first.iter().chain(second).cloned().collect()
}
fn assert_either_order_keeps_mtp_independent(inherited: &[String], mtp: &[String]) {
let expected = OperatorSources {
kar: None,
mtp: Some(("pack".into(), "private".into())),
inherited: Some((9, "proof.json".into())),
kar_file: None,
};
for args in [joined(inherited, mtp), joined(mtp, inherited)] {
assert_eq!(operator_sources_with_inherited(&args).unwrap(), expected);
}
}
fn assert_exclusive(inherited: &[String]) {
let kar = ["--kar-archive", "archive", "--kar-staging", "private"].map(String::from);
assert!(operator_sources_with_inherited(&joined(inherited, &kar)).is_err());
assert!(operator_sources_with_inherited(&joined(inherited, inherited)).is_err());
}
fn assert_descriptor_bounded(inherited: &[String; 4]) {
for fd in ["", "0", "1", "2", "-3", "+9", " 9", "1048577", "4294967296"] {
let mut invalid = inherited.clone();
invalid[1] = fd.into();
assert!(operator_sources_with_inherited(&invalid).is_err());
}
}
fn assert_malformed_refused(inherited: &[String; 4]) {
for length in [1, 2, 3] {
assert!(operator_sources_with_inherited(&inherited[..length]).is_err());
}
let mut invalid = inherited.clone();
invalid[2] = "--kar-staging".into();
assert!(operator_sources_with_inherited(&invalid).is_err());
invalid[2] = "--kar-provenance".into();
invalid[3].clear();
assert!(operator_sources_with_inherited(&invalid).is_err());
}
#[test]
fn read_only_file_form_is_exclusive_with_the_fd_and_the_staged_forms() {
let file = read_only_file();
let mtp = mtp_pair();
let parsed = operator_sources_with_inherited(&joined(&file, &mtp)).unwrap();
assert_eq!(
parsed.kar_file,
Some(("/assets/a.kar".into(), "/assets/a.json".into()))
);
assert_eq!((parsed.inherited, parsed.kar), (None, None));
let fd = ["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from);
let staged = ["--kar-archive", "archive", "--kar-staging", "private"].map(String::from);
for other in [&fd, &staged, &file] {
assert!(
operator_sources_with_inherited(
&file.iter().chain(other).cloned().collect::<Vec<_>>()
)
.is_err()
);
for other in [&inherited_fd(), &staged, &file] {
assert!(operator_sources_with_inherited(&joined(&file, other)).is_err());
}
let mut invalid = file.clone();
invalid[2] = "--kar-staging".into();
@@ -183,52 +234,11 @@ mod inherited_source_tests {
#[test]
fn inherited_kar_pair_is_bounded_exclusive_and_keeps_mtp_independent() {
let inherited =
["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from);
let mtp = ["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from);
let expected = OperatorSources {
kar: None,
mtp: Some(("pack".into(), "private".into())),
inherited: Some((9, "proof.json".into())),
kar_file: None,
};
for args in [
inherited.iter().chain(&mtp).cloned().collect::<Vec<_>>(),
mtp.iter().chain(&inherited).cloned().collect(),
] {
assert_eq!(operator_sources_with_inherited(&args).unwrap(), expected);
}
let kar = ["--kar-archive", "archive", "--kar-staging", "private"].map(String::from);
assert!(
operator_sources_with_inherited(
&inherited.iter().chain(&kar).cloned().collect::<Vec<_>>()
)
.is_err()
);
assert!(
operator_sources_with_inherited(
&inherited
.iter()
.chain(&inherited)
.cloned()
.collect::<Vec<_>>()
)
.is_err()
);
for fd in ["", "0", "1", "2", "-3", "+9", " 9", "1048577", "4294967296"] {
let mut invalid = inherited.clone();
invalid[1] = fd.into();
assert!(operator_sources_with_inherited(&invalid).is_err());
}
for length in [1, 2, 3] {
assert!(operator_sources_with_inherited(&inherited[..length]).is_err());
}
let mut invalid = inherited.clone();
invalid[2] = "--kar-staging".into();
assert!(operator_sources_with_inherited(&invalid).is_err());
invalid[2] = "--kar-provenance".into();
invalid[3].clear();
assert!(operator_sources_with_inherited(&invalid).is_err());
let inherited = inherited_fd();
assert_either_order_keeps_mtp_independent(&inherited, &mtp_pair());
assert_exclusive(&inherited);
assert_descriptor_bounded(&inherited);
assert_malformed_refused(&inherited);
assert_eq!(
operator_sources_with_inherited(&[]).unwrap(),
OperatorSources {
@@ -0,0 +1,196 @@
//! The start-up arguments: verification flags, the fixed 14-item base, the endpoint and the engine config.
use super::*;
/// The operator's whole command line, parsed and checked; nothing is started yet.
pub(super) struct Operator {
pub(super) address: SocketAddr,
pub(super) token: String,
pub(super) config: NativeBackendConfig,
pub(super) requested_mode: Option<OriginalServeMode>,
pub(super) original_options: OriginalServeOptions,
pub(super) selection: Selection,
}
/// The seven `--flag VALUE` pairs every start carries, in this order.
struct BaseArguments<'a> {
address: &'a str,
token_env: &'a str,
shard0: &'a str,
shard1: &'a str,
gpu: &'a str,
budget: &'a str,
context: &'a str,
}
const BASE_FLAGS: [&str; 7] = [
"--listen",
"--token-env",
"--shard0",
"--shard1",
"--gpu",
"--gpu-budget",
"--context-tokens",
];
/// Remove `name` from `args` and say whether it was there.
fn take_flag(args: &mut Vec<String>, name: &str) -> bool {
let given = args.iter().any(|arg| arg == name);
args.retain(|arg| arg != name);
given
}
/// `--verify-only`: run the load-time source verification (shards, KAR archive) and exit; no CUDA is touched.
///
/// Also applies the verification flags of the process (`--kar-attested-by-stamp`, `--verify-stamps`) and returns
/// `--verify-only` and the digest of `--kar-sparse-extents-sha256`.
pub(super) fn take_verification_flags(
args: &mut Vec<String>,
) -> Result<(bool, Option<[u8; 32]>), Failure> {
let verify_only = take_flag(args, "--verify-only");
// `--verify-stamps DIR [--verify-rehash]`: a file that already matched its pinned digest and is unchanged
// (device, inode, size, mtime, ctime) is not hashed again; `--verify-rehash` hashes everything and renews
// the stamps. Without `--verify-stamps` every start verifies in full.
let verify_rehash = take_flag(args, "--verify-rehash");
if take_flag(args, "--kar-attested-by-stamp") {
// Only `leleka run` passes this, after matching the stamp of the archive file it copied the memfd from.
set_archive_attested();
}
// `--kar-sparse-extents-sha256 HEX` (only `leleka run` passes it, `memfd_extents: ple_only`, the form of
// rtx5090-32g): the sealed memfd holds only the byte ranges the serve path reads, and is verified against
// the pinned digest of those ranges.
let sparse_extents = take_option(args, "--kar-sparse-extents-sha256")?
.map(|text| parse_sha256(&text))
.transpose()?;
configure_verify_stamps(args, verify_rehash)?;
Ok((verify_only, sparse_extents))
}
fn configure_verify_stamps(args: &mut Vec<String>, rehash: bool) -> Result<(), Failure> {
match take_option(args, "--verify-stamps")? {
Some(directory) if directory.is_empty() => Err("invalid_verify_stamps".into()),
Some(directory) => {
set_verify_stamps(PathBuf::from(directory), rehash);
Ok(())
}
None if rehash => Err("verify_rehash_requires_verify_stamps".into()),
None => Ok(()),
}
}
/// Split the 14 base items from the optional rest.
pub(super) fn split_arguments(args: &[String]) -> Result<(&[String], &[String]), Failure> {
if args.len() >= 14 {
Ok(args.split_at(14))
} else {
Err("invalid_inference_arguments".into())
}
}
/// Parse and check the whole command line (the part after the process flags).
pub(super) fn parse_operator(
args: &[String],
sparse_extents: Option<[u8; 32]>,
) -> Result<Operator, Failure> {
let (base, extra) = split_arguments(args)?;
let (requested_mode, original_options, extra) = operator_original_serve(extra)?;
let (selection, source_args) = select_execution(&extra)?;
let sources = operator_sources_with_inherited(&source_args)?;
let base = base_arguments(base)?;
let address = listen_address(base.address)?;
let token = runtime_credential(base.token_env)?;
let config = native_config(&base, sources, sparse_extents)?;
Ok(Operator {
address,
token,
config,
requested_mode,
original_options,
selection,
})
}
fn flags_in_order(base: &[String]) -> bool {
let flags = BASE_FLAGS.iter().enumerate();
base.len() == 14
&& flags
.into_iter()
.all(|(index, flag)| base[2 * index] == *flag)
}
fn base_arguments(base: &[String]) -> Result<BaseArguments<'_>, Failure> {
if !flags_in_order(base) {
return Err("invalid_inference_arguments".into());
}
Ok(BaseArguments {
address: &base[1],
token_env: &base[3],
shard0: &base[5],
shard1: &base[7],
gpu: &base[9],
budget: &base[11],
context: &base[13],
})
}
fn listen_address(text: &str) -> Result<SocketAddr, Failure> {
let address: SocketAddr = text.parse().map_err(|_| "invalid_runtime_endpoint")?;
if !address.ip().is_loopback() {
return Err("loopback_required".into());
}
Ok(address)
}
/// The runtime credential, read from the environment variable `name`.
fn runtime_credential(name: &str) -> Result<String, Failure> {
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return Err("invalid_token_environment_name".into());
}
let token = std::env::var(name).map_err(|_| "missing_runtime_credential")?;
if !(32..=4096).contains(&token.len()) || !token.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
return Err("invalid_runtime_credential".into());
}
Ok(token)
}
fn native_config(
base: &BaseArguments<'_>,
sources: OperatorSources,
sparse_extents: Option<[u8; 32]>,
) -> Result<NativeBackendConfig, Failure> {
Ok(NativeBackendConfig {
shard0: PathBuf::from(base.shard0),
shard1: PathBuf::from(base.shard1),
gpu_device_ordinal: base.gpu.parse().map_err(|_| "invalid_gpu_ordinal")?,
gpu_budget_bytes: base.budget.parse().map_err(|_| "invalid_gpu_budget")?,
context_tokens: base.context.parse().map_err(|_| "invalid_context_bound")?,
kar_ple_source: sources.kar,
kar_ple_inherited: inherited_archive(sources.inherited, sources.kar_file, sparse_extents)?,
mtp_source: sources.mtp,
// The routed-expert KAR source has no operator flag in this binary yet.
kar_expert_source: None,
experimental: Default::default(),
})
}
/// The archive handed down as a descriptor or as a read-only file, if either was given.
fn inherited_archive(
inherited: Option<(u32, PathBuf)>,
kar_file: Option<(PathBuf, PathBuf)>,
sparse_extents: Option<[u8; 32]>,
) -> Result<Option<InheritedKarArchive>, Failure> {
Ok(match (inherited, kar_file) {
(Some((fd, provenance)), None) => Some(match sparse_extents {
Some(digest) => InheritedKarArchive::open_sparse(fd, provenance, digest)?,
None => InheritedKarArchive::open(fd, provenance)?,
}),
// Low-RAM form (docs/laptop-profile.md): an ordinary read-only file instead of a 55 GB sealed memfd.
(None, Some((file, provenance))) if sparse_extents.is_none() => {
Some(InheritedKarArchive::open_read_only_file(&file, provenance)?)
}
_ if sparse_extents.is_some() => {
return Err("kar_sparse_extents_requires_kar_archive_fd".into());
}
_ => None,
})
}
@@ -18,6 +18,35 @@ pub(super) fn operator_streamed_spill_execution(
#[cfg(test)]
mod streamed_spill_operator_tests {
use super::*;
fn assert_conflicts_refused() {
for flag in [
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
STREAMED_SPILL_FLAG,
] {
assert!(
operator_streamed_spill_execution(&[STREAMED_SPILL_FLAG.into(), flag.into()])
.is_err()
);
}
}
fn assert_values_stay_opaque() {
let opaque = [
"--kar-archive",
STREAMED_SPILL_FLAG,
"--kar-staging",
"/sanitized/stage",
]
.map(String::from);
let (selected, preserved) = operator_streamed_spill_execution(&opaque).unwrap();
assert!(!selected);
assert_eq!(preserved, opaque);
assert!(operator_streamed_spill_execution(&["--unpaired".into()]).is_err());
}
#[test]
fn streamed_selection_refuses_conflicts_and_does_not_scan_source_values() {
let args = [
@@ -34,27 +63,7 @@ mod streamed_spill_operator_tests {
assert!(queued);
let (optimized, profile, rest) = operator_optimized_execution(&parsed).unwrap();
assert!(optimized && profile.is_some() && rest.is_empty());
for flag in [
QUEUED_OWNERS_FLAG,
OPTIMIZED_FLAG,
INTEGER_WINDOWED_FLAG,
STREAMED_SPILL_FLAG,
] {
assert!(
operator_streamed_spill_execution(&[STREAMED_SPILL_FLAG.into(), flag.into()])
.is_err()
);
}
let opaque = [
"--kar-archive",
STREAMED_SPILL_FLAG,
"--kar-staging",
"/sanitized/stage",
]
.map(String::from);
let (selected, preserved) = operator_streamed_spill_execution(&opaque).unwrap();
assert!(!selected);
assert_eq!(preserved, opaque);
assert!(operator_streamed_spill_execution(&["--unpaired".into()]).is_err());
assert_conflicts_refused();
assert_values_stay_opaque();
}
}
+56 -26
View File
@@ -15,13 +15,17 @@ fn main() {
std::process::exit(2);
}
#[cfg(target_os = "linux")]
const HELP: &str = concat!(
"leleka-seal-exec --file PATH [--expect-bytes N] -- COMMAND ARG... ",
"({FD} in an argument is replaced by the sealed descriptor number)"
);
#[cfg(target_os = "linux")]
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.as_slice() == ["--help"] {
println!(
"leleka-seal-exec --file PATH [--expect-bytes N] -- COMMAND ARG... ({{FD}} in an argument is replaced by the sealed descriptor number)"
);
println!("{HELP}");
return;
}
match linux::run(&args) {
@@ -73,35 +77,51 @@ mod linux {
index += 2;
}
"--expect-bytes" if expect_bytes.is_none() => {
expect_bytes = Some(
args.get(index + 1)
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| *value > 0)
.ok_or("--expect-bytes needs a positive integer")?,
);
expect_bytes = Some(byte_pin(args.get(index + 1))?);
index += 2;
}
"--" => {
let command = args[index + 1..].to_vec();
if command.is_empty() || !command.iter().any(|arg| arg.contains(PLACEHOLDER)) {
return Err(
"the command must be given after -- and use {FD} at least once".into(),
);
}
return Ok(Plan {
file: file.ok_or("--file is required")?,
expect_bytes,
command,
});
}
"--" => return finish_plan(file, expect_bytes, &args[index + 1..]),
other => return Err(format!("unexpected argument {other:?}")),
}
}
Err("missing -- before the command".into())
}
/// The operand of `--expect-bytes`: a positive integer.
fn byte_pin(operand: Option<&String>) -> Result<u64, String> {
operand
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| *value > 0)
.ok_or_else(|| "--expect-bytes needs a positive integer".into())
}
/// The plan, once the `--` separator and the command behind it are in.
fn finish_plan(
file: Option<PathBuf>,
expect_bytes: Option<u64>,
command: &[String],
) -> Result<Plan, String> {
let command = command.to_vec();
if command.is_empty() || !command.iter().any(|arg| arg.contains(PLACEHOLDER)) {
return Err("the command must be given after -- and use {FD} at least once".into());
}
Ok(Plan {
file: file.ok_or("--file is required")?,
expect_bytes,
command,
})
}
/// Copy `source` into a new sealed memfd. `expect_bytes` pins the exact length.
pub fn sealed_copy(source: &mut File, expect_bytes: Option<u64>) -> Result<File, String> {
let length = checked_length(source, expect_bytes)?;
let memory = copy_into_memfd(source, length)?;
seal(&memory)?;
Ok(memory)
}
/// The length of the regular file `source`, which must equal `expect_bytes` when given.
fn checked_length(source: &File, expect_bytes: Option<u64>) -> Result<u64, String> {
let metadata = source
.metadata()
.map_err(|e| format!("cannot inspect the file: {e}"))?;
@@ -116,6 +136,11 @@ mod linux {
metadata.len()
));
}
Ok(metadata.len())
}
/// Copy all of `source` (`length` bytes at the time of the check) into a fresh, still unsealed memfd.
fn copy_into_memfd(source: &mut File, length: u64) -> Result<File, String> {
// No MFD_CLOEXEC: the descriptor must survive the exec. Sealing needs MFD_ALLOW_SEALING.
let fd = memfd_create("leleka-sealed-archive", MemfdFlags::ALLOW_SEALING)
.map_err(|e| format!("memfd_create failed: {e}"))?;
@@ -134,17 +159,22 @@ mod linux {
.map_err(|e| format!("write to memfd failed: {e}"))?;
copied += count as u64;
}
if copied != metadata.len() {
if copied != length {
return Err("the file changed while it was being copied".into());
}
fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?;
if !fcntl_get_seals(&memory)
Ok(memory)
}
/// Add every seal and check that the kernel applied all of them.
fn seal(memory: &File) -> Result<(), String> {
fcntl_add_seals(memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?;
if !fcntl_get_seals(memory)
.map_err(|e| format!("cannot read seals: {e}"))?
.contains(SEALS)
{
return Err("the kernel did not apply every seal".into());
}
Ok(memory)
Ok(())
}
pub fn run(args: &[String]) -> Result<Infallible, String> {
+48
View File
@@ -0,0 +1,48 @@
//! Command line parts of the `strata-desktop` binary: one module per long-running command.
use std::{fs::File, io::Read};
pub(crate) mod node;
pub(crate) mod proxy;
pub(crate) mod tunnel;
pub(crate) mod worker;
pub(crate) const HELP: &str = concat!(
"strata-desktop hardware\n",
"strata-desktop plan REQUIREMENTS.json [--hardware SNAPSHOT.json]\n",
"strata-desktop remote-inspect SSH_PROFILE.json\n",
"strata-desktop ssh-tunnel TUNNEL_PROFILE.json\n",
"strata-desktop remote-install INSTALL.json\n",
"strata-desktop remote-activate ACTIVATION.json\n",
"strata-desktop validate-worker WORKER.json\n",
"strata-desktop gateway POOL.json\n",
"strata-desktop node --listen 127.0.0.1:0 --token-env ENV [--pool POOL.json | --worker-profile FILE ",
"[--journal PRIVATE_PATH] | --stdio-lifetime]\n",
"strata-desktop node-proxy --listen 127.0.0.1:18765 --node 127.0.0.1:18766 --token-env ENV\n",
"strata-desktop worker --node 127.0.0.1:18766 --token-env ENV status|start UUID|stop UUID|operation UUID\n",
"Inventory and planning are read-only. Gateway serves configured loopback workers; it does not start or ",
"replace models."
);
pub(crate) fn read_json<T: serde::de::DeserializeOwned>(
path: &str,
) -> Result<T, Box<dyn std::error::Error>> {
let mut data = Vec::new();
File::open(path)?
.take(1024 * 1024 + 1)
.read_to_end(&mut data)?;
if data.len() > 1024 * 1024 {
return Err("input JSON exceeds 1 MiB".into());
}
Ok(serde_json::from_slice(&data)?)
}
/// A receiver that fires once standard input reaches end of file (the parent process is gone).
pub(crate) fn stdin_closed() -> tokio::sync::oneshot::Receiver<()> {
let (closed_tx, closed_rx) = tokio::sync::oneshot::channel();
std::thread::spawn(move || {
let mut byte = [0];
while std::io::stdin().read(&mut byte).is_ok_and(|n| n > 0) {}
let _ = closed_tx.send(());
});
closed_rx
}
+108
View File
@@ -0,0 +1,108 @@
//! `node`: serves a node agent on a loopback address.
use std::io::Write;
use strata_desktop_core::{gateway, managed_worker::Profile, node};
type Failure = Box<dyn std::error::Error>;
const USAGE: &str = concat!(
"usage: node --listen LOOPBACK:PORT --token-env ENV [--pool FILE | --worker-profile FILE ",
"[--journal PRIVATE_PATH] | --stdio-lifetime]"
);
/// What the node serves: a managed worker (with an optional journal), a gateway pool or nothing.
struct Mode<'a> {
profile: Option<Profile>,
journal: Option<&'a std::path::Path>,
gateway: Option<gateway::Gateway>,
stdio_lifetime: bool,
}
impl Mode<'_> {
fn none() -> Self {
Mode {
profile: None,
journal: None,
gateway: None,
stdio_lifetime: false,
}
}
}
pub(crate) async fn serve(args: &[String]) -> Result<(), Failure> {
let (address, token_env, mode) = match args {
[a, address, t, token_env, rest @ ..] if a == "--listen" && t == "--token-env" => {
(address, token_env, rest)
}
_ => return Err(USAGE.into()),
};
let address: std::net::SocketAddr = address.parse()?;
if !address.ip().is_loopback() {
return Err("node must bind loopback".into());
}
check_credential_name(token_env)?;
let token = std::env::var(token_env).map_err(|_| "missing node credential")?;
let Mode {
profile,
journal,
gateway,
stdio_lifetime,
} = parse_mode(mode, &token)?;
let agent = if let Some(profile) = profile {
node::Agent::managed_journal(token, profile, journal)?
} else {
node::Agent::new(token, gateway)?
};
let listener = tokio::net::TcpListener::bind(address).await?;
println!(
"{}",
serde_json::json!({"schema_version":1,"endpoint":format!("http://{}",listener.local_addr()?)})
);
std::io::stdout().flush()?;
let closed = stdio_lifetime.then(super::stdin_closed);
agent.serve(listener, shutdown(closed)).await
}
fn check_credential_name(name: &str) -> Result<(), Failure> {
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return Err("invalid credential variable name".into());
}
Ok(())
}
fn parse_mode<'a>(mode: &'a [String], token: &str) -> Result<Mode<'a>, Failure> {
Ok(match mode {
[p, file, j, path] if p == "--worker-profile" && j == "--journal" => Mode {
profile: Some(super::read_json(file)?),
journal: Some(std::path::Path::new(path)),
..Mode::none()
},
[p, file] if p == "--worker-profile" => Mode {
profile: Some(super::read_json(file)?),
..Mode::none()
},
[] => Mode::none(),
[s] if s == "--stdio-lifetime" => Mode {
stdio_lifetime: true,
..Mode::none()
},
[p, file] if p == "--pool" => Mode {
gateway: Some(gateway::Gateway::with_token(
super::read_json(file)?,
token.to_string(),
)?),
..Mode::none()
},
_ => return Err("invalid node mode; stdio lifetime cannot own inference".into()),
})
}
async fn shutdown(closed: Option<tokio::sync::oneshot::Receiver<()>>) {
match closed {
Some(closed_rx) => {
let _ = closed_rx.await;
}
None => {
let _ = tokio::signal::ctrl_c().await;
}
}
}
+20
View File
@@ -0,0 +1,20 @@
//! `node-proxy`: a loopback HTTP front for a remote node.
pub(crate) async fn run(
listen: &str,
address: &str,
token_env: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let listen: std::net::SocketAddr = listen.parse()?;
if !listen.ip().is_loopback() {
return Err("proxy must bind loopback".into());
}
let token = std::env::var(token_env).map_err(|_| "missing node credential")?;
let proxy = strata_desktop_core::node_proxy::Proxy::connect(address.parse()?, token).await?;
let listener = tokio::net::TcpListener::bind(listen).await?;
axum::serve(listener, proxy.router())
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
+51
View File
@@ -0,0 +1,51 @@
//! `ssh-tunnel`: serves one SSH tunnel until interrupted (or, with `--stdio-lifetime`, until stdin closes).
use std::io::{BufRead, Read, Write};
type Failure = Box<dyn std::error::Error>;
pub(crate) async fn run(file: &str) -> Result<(), Failure> {
let stdio_lifetime = file == "--stdio-lifetime";
let config = if stdio_lifetime {
read_bootstrap()?
} else {
super::read_json(file)?
};
let tunnel = strata_desktop_core::ssh_tunnel::Tunnel::bind(&config).await?;
let closed = stdio_lifetime.then(super::stdin_closed);
let endpoint = format!("http://{}", tunnel.address());
println!(
"{}",
serde_json::json!({
"schema_version": 1,
"endpoint": endpoint,
"transport": "ssh",
"readiness": "requires_authenticated_node_handshake"
})
);
std::io::stdout().flush()?;
tunnel.serve(shutdown(closed)).await.map_err(Into::into)
}
/// One newline-terminated JSON line on stdin, at most 1 MiB.
fn read_bootstrap<T: serde::de::DeserializeOwned>() -> Result<T, Failure> {
let mut line = Vec::new();
std::io::stdin()
.lock()
.take(1024 * 1024 + 1)
.read_until(b'\n', &mut line)?;
if line.len() > 1024 * 1024 || line.last() != Some(&b'\n') {
return Err("invalid tunnel bootstrap size or framing".into());
}
Ok(serde_json::from_slice(&line)?)
}
async fn shutdown(closed: Option<tokio::sync::oneshot::Receiver<()>>) {
match closed {
Some(closed_rx) => {
tokio::select! { _ = closed_rx => {}, _ = tokio::signal::ctrl_c() => {} }
}
None => {
let _ = tokio::signal::ctrl_c().await;
}
}
}
+87
View File
@@ -0,0 +1,87 @@
//! `worker`: one status, start, stop or operation query against a node.
use strata_desktop_core::node::{self, proto::*};
type Failure = Box<dyn std::error::Error>;
type Client = node_client::NodeClient<tonic::transport::Channel>;
const USAGE: &str =
"worker --node LOOPBACK:PORT --token-env ENV status|start UUID|stop UUID|operation UUID";
pub(crate) async fn run(args: &[String]) -> Result<(), Failure> {
let [n, address, t, env, action, rest @ ..] = args else {
return Err(USAGE.into());
};
if n != "--node" || t != "--token-env" {
return Err("invalid worker options".into());
}
let token = std::env::var(env).map_err(|_| "missing node credential")?;
let mut client = node::connect(address.parse()?).await?;
let value = match (action.as_str(), rest) {
("status", []) => status(&mut client, &token).await?,
("start" | "stop", [id]) => control(&mut client, &token, action, id).await?,
("operation", [id]) => operation(&mut client, &token, id).await?,
_ => {
return Err("invalid worker action; supply a stable operation UUID for commands".into());
}
};
println!("{}", serde_json::to_string(&value)?);
Ok(())
}
fn worker_request<T>(message: T, token: &str) -> Result<tonic::Request<T>, tonic::Status> {
let mut request = node::authorized(message, token)?;
request.set_timeout(std::time::Duration::from_secs(5));
Ok(request)
}
async fn status(client: &mut Client, token: &str) -> Result<serde_json::Value, Failure> {
let s = client
.worker_status(worker_request(Empty {}, token)?)
.await?
.into_inner();
Ok(
serde_json::json!({"profile_id":s.profile_id,"model":s.model,"phase":s.phase,"pid":s.pid,"reason":s.reason}),
)
}
async fn control(
client: &mut Client,
token: &str,
action: &str,
id: &str,
) -> Result<serde_json::Value, Failure> {
let hello = Hello {
protocol_version: 1,
};
let epoch = client
.handshake(worker_request(hello, token)?)
.await?
.into_inner()
.agent_epoch;
let command = WorkerCommand {
operation_id: id.to_string(),
expected_epoch: epoch,
action: if action == "start" { 1 } else { 2 },
drain_timeout_ms: if action == "stop" { 30000 } else { 0 },
};
let s = client
.control_worker(worker_request(command, token)?)
.await?
.into_inner();
Ok(serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason}))
}
async fn operation(
client: &mut Client,
token: &str,
id: &str,
) -> Result<serde_json::Value, Failure> {
let query = OperationQuery {
operation_id: id.to_string(),
};
let s = client
.operation_status(worker_request(query, token)?)
.await?
.into_inner();
Ok(serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason}))
}
+98 -76
View File
@@ -101,11 +101,8 @@ pub fn observer_adaptive_slots(path: PathBuf) -> Result<EvaluationObserver, &'st
)
}
fn observer_output(
execution_policy: &'static str,
path: PathBuf,
evaluation_nonce: Option<String>,
) -> Result<EvaluationObserver, &'static str> {
/// The output file must be a fresh `measurements.jsonl` in a private, real, absolute directory.
fn check_output_directory(path: &std::path::Path) -> Result<(), &'static str> {
if !path.is_absolute() || path.file_name().is_none_or(|n| n != "measurements.jsonl") {
return Err("invalid_evaluation_output");
}
@@ -128,6 +125,15 @@ fn observer_output(
{
return Err("invalid_evaluation_directory");
}
Ok(())
}
fn observer_output(
execution_policy: &'static str,
path: PathBuf,
evaluation_nonce: Option<String>,
) -> Result<EvaluationObserver, &'static str> {
check_output_directory(&path)?;
// create_new rejects an existing file or final symlink; no truncation/append.
let mut options = OpenOptions::new();
options.write(true).create_new(true);
@@ -178,77 +184,8 @@ impl Output {
) -> Result<(), ()> {
let mut encoded = BoundedBuffer(Vec::new());
match result {
Ok(measurement) => {
if measurement.input_token_ids.len() > 262144
|| measurement.output_token_ids.len() > 4096
|| measurement.windows.len() > 4096
|| measurement.retained_prefix_tokens > measurement.input_token_ids.len()
|| measurement
.input_token_ids
.iter()
.chain(&measurement.output_token_ids)
.any(|id| *id >= 248320)
{
return Err(());
}
let mut windows = Vec::new();
windows
.try_reserve_exact(measurement.windows.len())
.map_err(|_| ())?;
for witness in &measurement.windows {
if witness.verified_count > 4
|| witness.draft_steps > 4
|| witness.accepted_non_eos_drafts
!= witness.verified_count.saturating_sub(1)
|| witness.accepted_non_eos_drafts > witness.draft_steps
|| witness.verified_ids[..witness.verified_count]
.iter()
.any(|id| *id >= 248320)
{
return Err(());
}
windows.push(WindowView::from(witness));
}
let record = Record {
schema: "leleka_actual_owner_measurement_v1",
execution_policy: self.execution_policy,
evaluation_nonce: self.evaluation_nonce.as_deref(),
index: self.records,
status: "measurement",
input_token_ids: &measurement.input_token_ids,
output_token_ids: &measurement.output_token_ids,
retained_prefix_tokens: measurement.retained_prefix_tokens,
prefill_ns: u64::try_from(measurement.prefill.as_nanos()).map_err(|_| ())?,
decode_ns: u64::try_from(measurement.decode.as_nanos()).map_err(|_| ())?,
windows: &windows,
cache_before: CacheView::from(measurement.cache_before),
cache_after: CacheView::from(measurement.cache_after),
completed: measurement.completed,
stopped: measurement.stopped,
terminal_published: measurement.terminal_published,
};
serde_json::to_writer(&mut encoded, &record).map_err(|_| ())?;
}
Err(failure) => {
let failure = match failure {
MeasurementFailure::Bounds => "bounds",
MeasurementFailure::Allocation => "allocation",
MeasurementFailure::Incomplete => "incomplete",
MeasurementFailure::CounterRewind => "counter_rewind",
};
serde_json::to_writer(
&mut encoded,
&Refusal {
schema: "leleka_actual_owner_measurement_v1",
execution_policy: self.execution_policy,
evaluation_nonce: self.evaluation_nonce.as_deref(),
index: self.records,
status: "measurement_refused",
failure,
},
)
.map_err(|_| ())?;
}
Ok(measurement) => self.encode_measurement(&measurement, &mut encoded)?,
Err(failure) => self.encode_refusal(failure, &mut encoded)?,
}
encoded.write_all(b"\n").map_err(|_| ())?;
let next = self
@@ -264,6 +201,91 @@ impl Output {
self.records += 1;
Ok(())
}
fn encode_measurement(
&self,
measurement: &EvaluationMeasurement,
encoded: &mut BoundedBuffer,
) -> Result<(), ()> {
if !measurement_in_bounds(measurement) {
return Err(());
}
let windows = window_views(measurement)?;
let record = Record {
schema: "leleka_actual_owner_measurement_v1",
execution_policy: self.execution_policy,
evaluation_nonce: self.evaluation_nonce.as_deref(),
index: self.records,
status: "measurement",
input_token_ids: &measurement.input_token_ids,
output_token_ids: &measurement.output_token_ids,
retained_prefix_tokens: measurement.retained_prefix_tokens,
prefill_ns: u64::try_from(measurement.prefill.as_nanos()).map_err(|_| ())?,
decode_ns: u64::try_from(measurement.decode.as_nanos()).map_err(|_| ())?,
windows: &windows,
cache_before: CacheView::from(measurement.cache_before),
cache_after: CacheView::from(measurement.cache_after),
completed: measurement.completed,
stopped: measurement.stopped,
terminal_published: measurement.terminal_published,
};
serde_json::to_writer(encoded, &record).map_err(|_| ())
}
fn encode_refusal(
&self,
failure: MeasurementFailure,
encoded: &mut BoundedBuffer,
) -> Result<(), ()> {
let failure = match failure {
MeasurementFailure::Bounds => "bounds",
MeasurementFailure::Allocation => "allocation",
MeasurementFailure::Incomplete => "incomplete",
MeasurementFailure::CounterRewind => "counter_rewind",
};
let refusal = Refusal {
schema: "leleka_actual_owner_measurement_v1",
execution_policy: self.execution_policy,
evaluation_nonce: self.evaluation_nonce.as_deref(),
index: self.records,
status: "measurement_refused",
failure,
};
serde_json::to_writer(encoded, &refusal).map_err(|_| ())
}
}
/// Whether the sizes and token ids of a measurement are inside the closed record bounds.
fn measurement_in_bounds(measurement: &EvaluationMeasurement) -> bool {
measurement.input_token_ids.len() <= 262144
&& measurement.output_token_ids.len() <= 4096
&& measurement.windows.len() <= 4096
&& measurement.retained_prefix_tokens <= measurement.input_token_ids.len()
&& !measurement
.input_token_ids
.iter()
.chain(&measurement.output_token_ids)
.any(|id| *id >= 248320)
}
/// Whether one verification window is internally consistent and uses valid token ids.
fn window_in_bounds(witness: &WindowWitness) -> bool {
witness.verified_count <= 4
&& witness.draft_steps <= 4
&& witness.accepted_non_eos_drafts == witness.verified_count.saturating_sub(1)
&& witness.accepted_non_eos_drafts <= witness.draft_steps
&& !witness.verified_ids[..witness.verified_count]
.iter()
.any(|id| *id >= 248320)
}
fn window_views(measurement: &EvaluationMeasurement) -> Result<Vec<WindowView>, ()> {
let mut windows = Vec::new();
windows
.try_reserve_exact(measurement.windows.len())
.map_err(|_| ())?;
for witness in &measurement.windows {
if !window_in_bounds(witness) {
return Err(());
}
windows.push(WindowView::from(witness));
}
Ok(windows)
}
struct BoundedBuffer(Vec<u8>);
impl Write for BoundedBuffer {
+23 -196
View File
@@ -3,216 +3,43 @@
#[allow(unused_imports)]
use super::*;
mod relay;
mod request;
mod upstream;
use relay::{buffer_body, relay_stream};
use request::{admit, parse_request, select_deployments};
use upstream::{response_headers, send_upstream, stream_kind};
pub(super) async fn responses(State(g): State<Gateway>, h: HeaderMap, body: Bytes) -> Response {
if !g.authorized(&h) {
return error(StatusCode::UNAUTHORIZED, "unauthorized");
}
let mut v: Value = match serde_json::from_slice(&body) {
Ok(Value::Object(v)) => Value::Object(v),
_ => return error(StatusCode::BAD_REQUEST, "invalid_json"),
};
if v.get("conversation").is_some_and(|v| !v.is_null())
|| v.get("background") == Some(&Value::Bool(true))
{
return error(StatusCode::BAD_REQUEST, "unsupported_stateful_mode");
match forward(g, body).await {
Ok(response) | Err(response) => response,
}
let Some(model) = v.get("model").and_then(Value::as_str) else {
return error(StatusCode::BAD_REQUEST, "model_required");
};
let mut eligible: Vec<_> =
g.0.config
.deployments
.iter()
.enumerate()
.filter(|(_, d)| {
d.id == model
|| g.0
.config
.aliases
.get(model)
.is_some_and(|m| m.contains(&d.id))
})
.map(|(i, _)| i)
.collect();
if eligible.is_empty() {
return error(StatusCode::NOT_FOUND, "unknown_model");
}
let mut caps = HashSet::from(["responses"]);
required_caps(v.get("input").unwrap_or(&Value::Null), &mut caps);
if v.get("tools")
.is_some_and(|v| v.as_array().is_none_or(|a| !a.is_empty()))
{
caps.insert("tools");
}
if v.get("reasoning").is_some_and(|v| !v.is_null()) {
caps.insert("reasoning");
}
if v.pointer("/text/format/type")
.and_then(Value::as_str)
.is_some_and(|s| s != "text")
{
caps.insert("structured_output");
}
eligible.retain(|i| {
caps.iter().all(|c| {
g.0.config.deployments[*i]
.capabilities
.iter()
.any(|x| x == c)
})
});
if let Some(previous) = v.get("previous_response_id").filter(|v| !v.is_null()) {
let owner = previous.as_str().and_then(|id| {
g.0.owners
.lock()
.unwrap()
.iter()
.find(|(key, _)| key == id)
.map(|(_, w)| *w)
});
let Some(owner) = owner else {
return error(StatusCode::CONFLICT, "unknown_response_owner");
};
eligible.retain(|i| *i == owner);
}
if eligible.is_empty() {
return error(StatusCode::CONFLICT, "no_compatible_deployment");
}
let lease = match g
.0
.pool
.acquire(eligible, Duration::from_millis(g.0.config.queue_timeout_ms))
.await
{
Ok(l) => l,
Err(AdmissionError::Full) => return error(StatusCode::TOO_MANY_REQUESTS, "queue_full"),
Err(AdmissionError::Expired) => return error(StatusCode::GATEWAY_TIMEOUT, "queue_timeout"),
Err(_) => return error(StatusCode::SERVICE_UNAVAILABLE, "admission_failed"),
};
let worker = lease.worker();
let mut guard = InFlight {
g: g.clone(),
worker,
lease: Some(lease),
complete: false,
};
}
async fn forward(g: Gateway, body: Bytes) -> Result<Response, Response> {
let mut v = parse_request(&body)?;
let eligible = select_deployments(&g, &v)?;
let mut guard = admit(&g, eligible).await?;
let worker = guard.worker;
let d = &g.0.config.deployments[worker];
v["model"] = Value::String(d.model.clone());
let streaming = v.get("stream") == Some(&Value::Bool(true));
let deadline =
tokio::time::Instant::now() + Duration::from_millis(g.0.config.request_timeout_ms);
let mut request =
g.0.client
.post(format!("{}/v1/responses", d.endpoint.trim_end_matches('/')))
.header("content-type", "application/json")
.body(serde_json::to_vec(&v).unwrap());
if let Some(token) = &g.0.upstream_tokens[worker] {
request = request.bearer_auth(token);
}
let response = match tokio::time::timeout_at(deadline, request.send()).await {
Ok(Ok(r)) => r,
_ => return error(StatusCode::BAD_GATEWAY, "upstream_unavailable"),
};
let response = send_upstream(&g, worker, &v, deadline).await?;
let code = response.status();
let is_sse = response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|s| s.starts_with("text/event-stream"));
if code.is_success() && streaming && !is_sse {
return error(StatusCode::BAD_GATEWAY, "upstream_stream_type");
}
let content_type = if is_sse {
"text/event-stream"
} else {
"application/json"
};
let is_sse = stream_kind(&response, code, streaming)?;
let mut result = if streaming && code.is_success() {
let stream = response.bytes_stream();
let stream = futures_util::stream::unfold(
(Box::pin(stream), guard, Terminal::default(), false),
move |(mut source, mut guard, mut terminal, done)| async move {
if done {
return None;
}
match tokio::time::timeout_at(deadline, source.next()).await {
Ok(Some(Ok(bytes))) => {
terminal.feed(&bytes);
if let Some(id) = terminal.response_id.take() {
guard.g.remember(id, guard.worker);
}
Some((
Ok::<_, std::io::Error>(bytes),
(source, guard, terminal, false),
))
}
Ok(None) => {
guard.complete = terminal.complete;
if terminal.complete {
if let Some(id) = terminal.response_id.take() {
guard.g.remember(id, guard.worker);
}
None
} else {
Some((
Err(std::io::Error::other("upstream missing terminal event")),
(source, guard, terminal, true),
))
}
}
_ => Some((
Err(std::io::Error::other("upstream stream interrupted")),
(source, guard, terminal, true),
)),
}
},
);
(code, Body::from_stream(stream)).into_response()
relay_stream(response, guard, deadline)
} else {
let mut data = Vec::new();
let mut stream = response.bytes_stream();
loop {
match tokio::time::timeout_at(deadline, stream.next()).await {
Ok(Some(Ok(bytes))) if data.len() + bytes.len() <= 8 * 1024 * 1024 => {
data.extend_from_slice(&bytes)
}
Ok(None) => break,
_ => return error(StatusCode::BAD_GATEWAY, "upstream_body_failed"),
}
}
if code.is_success() {
let parsed = serde_json::from_slice::<Value>(&data).ok();
if !matches!(
parsed
.as_ref()
.and_then(|v| v.get("status"))
.and_then(Value::as_str),
Some("completed" | "failed" | "incomplete")
) {
return error(StatusCode::BAD_GATEWAY, "upstream_missing_terminal_status");
}
if let Some(id) = parsed
.as_ref()
.and_then(|v| v.get("id"))
.and_then(Value::as_str)
{
g.remember(id.into(), worker);
}
}
guard.complete = true;
(code, Body::from(data)).into_response()
buffer_body(&g, response, &mut guard, deadline).await?
};
result
.headers_mut()
.insert("content-type", content_type.parse().unwrap());
result
.headers_mut()
.insert("cache-control", "no-store".parse().unwrap());
// IDs are validated as HTTP values instead of panicking on administrator input.
if let Ok(id) = d.id.parse() {
result.headers_mut().insert("x-strata-deployment", id);
}
result
response_headers(&mut result, is_sse, &d.id);
Ok(result)
}
pub async fn serve(config: Config) -> Result<(), Box<dyn std::error::Error>> {
+124
View File
@@ -0,0 +1,124 @@
//! The response body of the pool gateway: relay a stream with its terminal tracking, or buffer a bounded body.
#[allow(unused_imports)]
use super::*;
use std::pin::Pin;
/// The state a relayed stream threads from chunk to chunk.
struct Relay<S> {
source: Pin<Box<S>>,
guard: InFlight,
terminal: Terminal,
done: bool,
}
type Chunk<S> = (Result<Bytes, std::io::Error>, Relay<S>);
fn remember_terminal(guard: &InFlight, terminal: &mut Terminal) {
if let Some(id) = terminal.response_id.take() {
guard.g.remember(id, guard.worker);
}
}
async fn next_chunk<S>(deadline: tokio::time::Instant, mut r: Relay<S>) -> Option<Chunk<S>>
where
S: futures_util::Stream<Item = Result<Bytes, reqwest::Error>>,
{
if r.done {
return None;
}
match tokio::time::timeout_at(deadline, r.source.next()).await {
Ok(Some(Ok(bytes))) => {
r.terminal.feed(&bytes);
remember_terminal(&r.guard, &mut r.terminal);
Some((Ok(bytes), r))
}
Ok(None) => {
r.guard.complete = r.terminal.complete;
if r.terminal.complete {
remember_terminal(&r.guard, &mut r.terminal);
return None;
}
r.done = true;
Some((
Err(std::io::Error::other("upstream missing terminal event")),
r,
))
}
_ => {
r.done = true;
Some((Err(std::io::Error::other("upstream stream interrupted")), r))
}
}
}
pub(super) fn relay_stream(
response: reqwest::Response,
guard: InFlight,
deadline: tokio::time::Instant,
) -> Response {
let code = response.status();
let relay = Relay {
source: Box::pin(response.bytes_stream()),
guard,
terminal: Terminal::default(),
done: false,
};
let stream = futures_util::stream::unfold(relay, move |r| next_chunk(deadline, r));
(code, Body::from_stream(stream)).into_response()
}
async fn read_bounded(
response: reqwest::Response,
deadline: tokio::time::Instant,
) -> Result<Vec<u8>, Response> {
let mut data = Vec::new();
let mut stream = response.bytes_stream();
loop {
match tokio::time::timeout_at(deadline, stream.next()).await {
Ok(Some(Ok(bytes))) if data.len() + bytes.len() <= 8 * 1024 * 1024 => {
data.extend_from_slice(&bytes)
}
Ok(None) => return Ok(data),
_ => return Err(error(StatusCode::BAD_GATEWAY, "upstream_body_failed")),
}
}
}
/// A successful buffered answer must carry a terminal status; its id is remembered for follow-ups.
fn check_terminal_status(g: &Gateway, worker: usize, data: &[u8]) -> Result<(), Response> {
let parsed = serde_json::from_slice::<Value>(data).ok();
let status = parsed
.as_ref()
.and_then(|v| v.get("status"))
.and_then(Value::as_str);
if !matches!(status, Some("completed" | "failed" | "incomplete")) {
return Err(error(
StatusCode::BAD_GATEWAY,
"upstream_missing_terminal_status",
));
}
if let Some(id) = parsed
.as_ref()
.and_then(|v| v.get("id"))
.and_then(Value::as_str)
{
g.remember(id.into(), worker);
}
Ok(())
}
pub(super) async fn buffer_body(
g: &Gateway,
response: reqwest::Response,
guard: &mut InFlight,
deadline: tokio::time::Instant,
) -> Result<Response, Response> {
let code = response.status();
let data = read_bounded(response, deadline).await?;
if code.is_success() {
check_terminal_status(g, guard.worker, &data)?;
}
guard.complete = true;
Ok((code, Body::from(data)).into_response())
}
@@ -0,0 +1,122 @@
//! Request admission of the pool gateway: parse, select the eligible deployments, take a lease.
#[allow(unused_imports)]
use super::*;
pub(super) fn parse_request(body: &Bytes) -> Result<Value, Response> {
let v: Value = match serde_json::from_slice(body) {
Ok(Value::Object(v)) => Value::Object(v),
_ => return Err(error(StatusCode::BAD_REQUEST, "invalid_json")),
};
if v.get("conversation").is_some_and(|v| !v.is_null())
|| v.get("background") == Some(&Value::Bool(true))
{
return Err(error(StatusCode::BAD_REQUEST, "unsupported_stateful_mode"));
}
if v.get("model").and_then(Value::as_str).is_none() {
return Err(error(StatusCode::BAD_REQUEST, "model_required"));
}
Ok(v)
}
/// The deployments that serve the model (directly or by alias).
fn model_deployments(g: &Gateway, model: &str) -> Vec<usize> {
g.0.config
.deployments
.iter()
.enumerate()
.filter(|(_, d)| {
d.id == model
|| g.0
.config
.aliases
.get(model)
.is_some_and(|m| m.contains(&d.id))
})
.map(|(i, _)| i)
.collect()
}
fn required_capabilities(v: &Value) -> HashSet<&'static str> {
let mut caps = HashSet::from(["responses"]);
required_caps(v.get("input").unwrap_or(&Value::Null), &mut caps);
if v.get("tools")
.is_some_and(|v| v.as_array().is_none_or(|a| !a.is_empty()))
{
caps.insert("tools");
}
if v.get("reasoning").is_some_and(|v| !v.is_null()) {
caps.insert("reasoning");
}
if v.pointer("/text/format/type")
.and_then(Value::as_str)
.is_some_and(|s| s != "text")
{
caps.insert("structured_output");
}
caps
}
/// A follow-up request goes to the worker that owns the previous response.
fn previous_owner(g: &Gateway, v: &Value) -> Result<Option<usize>, Response> {
let Some(previous) = v.get("previous_response_id").filter(|v| !v.is_null()) else {
return Ok(None);
};
let owner = previous.as_str().and_then(|id| {
g.0.owners
.lock()
.unwrap()
.iter()
.find(|(key, _)| key == id)
.map(|(_, w)| *w)
});
match owner {
Some(owner) => Ok(Some(owner)),
None => Err(error(StatusCode::CONFLICT, "unknown_response_owner")),
}
}
pub(super) fn select_deployments(g: &Gateway, v: &Value) -> Result<Vec<usize>, Response> {
let model = v.get("model").and_then(Value::as_str).unwrap_or_default();
let mut eligible = model_deployments(g, model);
if eligible.is_empty() {
return Err(error(StatusCode::NOT_FOUND, "unknown_model"));
}
let caps = required_capabilities(v);
eligible.retain(|i| {
caps.iter().all(|c| {
g.0.config.deployments[*i]
.capabilities
.iter()
.any(|x| x == c)
})
});
if let Some(owner) = previous_owner(g, v)? {
eligible.retain(|i| *i == owner);
}
if eligible.is_empty() {
return Err(error(StatusCode::CONFLICT, "no_compatible_deployment"));
}
Ok(eligible)
}
pub(super) async fn admit(g: &Gateway, eligible: Vec<usize>) -> Result<InFlight, Response> {
let timeout = Duration::from_millis(g.0.config.queue_timeout_ms);
let lease = match g.0.pool.acquire(eligible, timeout).await {
Ok(l) => l,
Err(AdmissionError::Full) => {
return Err(error(StatusCode::TOO_MANY_REQUESTS, "queue_full"));
}
Err(AdmissionError::Expired) => {
return Err(error(StatusCode::GATEWAY_TIMEOUT, "queue_timeout"));
}
Err(_) => return Err(error(StatusCode::SERVICE_UNAVAILABLE, "admission_failed")),
};
let worker = lease.worker();
Ok(InFlight {
g: g.clone(),
worker,
lease: Some(lease),
complete: false,
})
}
@@ -0,0 +1,60 @@
//! The upstream call of the pool gateway: send the request, classify the answer, set the response headers.
#[allow(unused_imports)]
use super::*;
pub(super) async fn send_upstream(
g: &Gateway,
worker: usize,
v: &Value,
deadline: tokio::time::Instant,
) -> Result<reqwest::Response, Response> {
let d = &g.0.config.deployments[worker];
let mut request =
g.0.client
.post(format!("{}/v1/responses", d.endpoint.trim_end_matches('/')))
.header("content-type", "application/json")
.body(serde_json::to_vec(v).unwrap());
if let Some(token) = &g.0.upstream_tokens[worker] {
request = request.bearer_auth(token);
}
match tokio::time::timeout_at(deadline, request.send()).await {
Ok(Ok(r)) => Ok(r),
_ => Err(error(StatusCode::BAD_GATEWAY, "upstream_unavailable")),
}
}
/// Whether the answer is a server-sent event stream; a successful stream request must get one.
pub(super) fn stream_kind(
response: &reqwest::Response,
code: reqwest::StatusCode,
streaming: bool,
) -> Result<bool, Response> {
let is_sse = response
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|s| s.starts_with("text/event-stream"));
if code.is_success() && streaming && !is_sse {
return Err(error(StatusCode::BAD_GATEWAY, "upstream_stream_type"));
}
Ok(is_sse)
}
pub(super) fn response_headers(result: &mut Response, is_sse: bool, deployment: &str) {
let content_type = if is_sse {
"text/event-stream"
} else {
"application/json"
};
result
.headers_mut()
.insert("content-type", content_type.parse().unwrap());
result
.headers_mut()
.insert("cache-control", "no-store".parse().unwrap());
// IDs are validated as HTTP values instead of panicking on administrator input.
if let Ok(id) = deployment.parse() {
result.headers_mut().insert("x-strata-deployment", id);
}
}
+94 -71
View File
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn secret, impl Gateway, fn error, fn models, fn status, fn required_caps.
//! Moved out of the parent module by STRA-338: fn secret, impl Gateway, fn error, fn models, fn status,
//! fn required_caps.
#[allow(unused_imports)]
use super::*;
@@ -49,75 +50,10 @@ impl Gateway {
}
/// Explicit token injection is useful for an embedding host and isolated tests.
pub fn with_token(config: Config, token: String) -> Result<Self, String> {
if config.schema_version != 1
|| !config.listen.ip().is_loopback()
|| token.len() < 16
|| config.queue_timeout_ms == 0
|| config.queue_timeout_ms > 3_600_000
|| config.request_timeout_ms == 0
|| config.request_timeout_ms > 86_400_000
|| config.queue_limit > 64
|| config.aliases.len() > 256
{
return Err("invalid gateway limits or non-loopback bind".into());
}
let mut endpoints = HashSet::new();
for d in &config.deployments {
let u = reqwest::Url::parse(&d.endpoint).map_err(|_| "invalid endpoint")?;
let ip = u
.host_str()
.unwrap_or("")
.trim_matches(['[', ']'])
.parse::<IpAddr>()
.map_err(|_| "endpoint must use a loopback IP")?;
if !ip.is_loopback()
|| u.scheme() != "http"
|| u.path() != "/"
|| u.query().is_some()
|| u.fragment().is_some()
|| !u.username().is_empty()
|| u.password().is_some()
|| !endpoints.insert(u.to_string())
|| d.model.is_empty()
|| d.id.len() > 128
{
return Err("invalid, duplicate or non-loopback endpoint".into());
}
}
let ids: HashSet<_> = config.deployments.iter().map(|d| d.id.as_str()).collect();
for (alias, members) in &config.aliases {
if alias.is_empty()
|| ids.contains(alias.as_str())
|| members.is_empty()
|| members.len() > 256
|| members.iter().any(|m| !ids.contains(m.as_str()))
{
return Err("invalid pool alias".into());
}
}
let pool = Pool::new(
config
.deployments
.iter()
.map(|d| Worker {
id: d.id.clone(),
group: d.group.clone(),
slots: d.slots,
request_bytes: d.request_bytes,
})
.collect(),
config
.groups
.iter()
.map(|g| ResourceGroup {
id: g.id.clone(),
slots: g.slots,
available_bytes: g.available_bytes,
})
.collect(),
config.queue_limit,
)
.map_err(|_| "invalid resource capacity")?;
check_limits(&config, &token)?;
check_endpoints(&config)?;
check_aliases(&config)?;
let pool = build_pool(&config)?;
let upstream_tokens = config
.deployments
.iter()
@@ -204,7 +140,8 @@ pub(super) async fn models(State(g): State<Gateway>, h: HeaderMap) -> Response {
.iter()
.map(|d| d.id.clone())
.chain(g.0.config.aliases.keys().cloned());
Json(json!({"object":"list","data":ids.map(|id|json!({"id":id,"object":"model","owned_by":"configured-pool"})).collect::<Vec<_>>()})).into_response()
let data = ids.map(|id| json!({"id":id,"object":"model","owned_by":"configured-pool"}));
Json(json!({"object":"list","data":data.collect::<Vec<_>>()})).into_response()
}
pub(super) async fn status(State(g): State<Gateway>, h: HeaderMap) -> Response {
if !g.authorized(&h) {
@@ -239,3 +176,89 @@ pub(super) fn required_caps(v: &Value, out: &mut HashSet<&'static str>) {
_ => {}
}
}
fn check_limits(config: &Config, token: &str) -> Result<(), String> {
if config.schema_version != 1
|| !config.listen.ip().is_loopback()
|| token.len() < 16
|| config.queue_timeout_ms == 0
|| config.queue_timeout_ms > 3_600_000
|| config.request_timeout_ms == 0
|| config.request_timeout_ms > 86_400_000
|| config.queue_limit > 64
|| config.aliases.len() > 256
{
return Err("invalid gateway limits or non-loopback bind".into());
}
Ok(())
}
/// A plain `http://loopback-ip:port/` endpoint without credentials, query or fragment.
fn plain_loopback_endpoint(u: &reqwest::Url, ip: IpAddr) -> bool {
ip.is_loopback()
&& u.scheme() == "http"
&& u.path() == "/"
&& u.query().is_none()
&& u.fragment().is_none()
&& u.username().is_empty()
&& u.password().is_none()
}
fn check_endpoints(config: &Config) -> Result<(), String> {
let mut endpoints = HashSet::new();
for d in &config.deployments {
let u = reqwest::Url::parse(&d.endpoint).map_err(|_| "invalid endpoint")?;
let ip = u
.host_str()
.unwrap_or("")
.trim_matches(['[', ']'])
.parse::<IpAddr>()
.map_err(|_| "endpoint must use a loopback IP")?;
if !plain_loopback_endpoint(&u, ip)
|| !endpoints.insert(u.to_string())
|| d.model.is_empty()
|| d.id.len() > 128
{
return Err("invalid, duplicate or non-loopback endpoint".into());
}
}
Ok(())
}
fn check_aliases(config: &Config) -> Result<(), String> {
let ids: HashSet<_> = config.deployments.iter().map(|d| d.id.as_str()).collect();
for (alias, members) in &config.aliases {
if alias.is_empty()
|| ids.contains(alias.as_str())
|| members.is_empty()
|| members.len() > 256
|| members.iter().any(|m| !ids.contains(m.as_str()))
{
return Err("invalid pool alias".into());
}
}
Ok(())
}
fn build_pool(config: &Config) -> Result<Pool, String> {
let workers = config
.deployments
.iter()
.map(|d| Worker {
id: d.id.clone(),
group: d.group.clone(),
slots: d.slots,
request_bytes: d.request_bytes,
})
.collect();
let groups = config
.groups
.iter()
.map(|g| ResourceGroup {
id: g.id.clone(),
slots: g.slots,
available_bytes: g.available_bytes,
})
.collect();
Pool::new(workers, groups, config.queue_limit).map_err(|_| "invalid resource capacity".into())
}
+22 -15
View File
@@ -144,6 +144,27 @@ fn cpu_features() -> Vec<String> {
result
}
/// Reads at most 64 KiB of the probe's output, then waits for the probe to exit successfully.
async fn read_probe_output(
stdout: tokio::process::ChildStdout,
data: &mut Vec<u8>,
child: &mut tokio::process::Child,
) -> Result<(), &'static str> {
stdout
.take(65537)
.read_to_end(data)
.await
.map_err(|_| "probe read failed")?;
if data.len() > 65536 {
return Err("probe output too large");
}
let status = child.wait().await.map_err(|_| "probe wait failed")?;
if !status.success() {
return Err("probe exited unsuccessfully");
}
Ok(())
}
/// Fixed program/arguments from inventory only; no shell, prompts or process list.
async fn probe(program: &str, args: &[&str], limit: Duration) -> Result<String, String> {
let mut child = Command::new(program)
@@ -156,21 +177,7 @@ async fn probe(program: &str, args: &[&str], limit: Duration) -> Result<String,
.map_err(|_| "probe could not start".to_string())?;
let stdout = child.stdout.take().ok_or("missing probe output")?;
let mut data = Vec::new();
let read = async {
stdout
.take(65537)
.read_to_end(&mut data)
.await
.map_err(|_| "probe read failed")?;
if data.len() > 65536 {
return Err("probe output too large");
}
let status = child.wait().await.map_err(|_| "probe wait failed")?;
if !status.success() {
return Err("probe exited unsuccessfully");
}
Ok(())
};
let read = read_probe_output(stdout, &mut data, &mut child);
match tokio::time::timeout(limit, read).await {
Ok(Ok(())) => String::from_utf8(data).map_err(|_| "probe output is not UTF-8".into()),
outcome => {
+60 -251
View File
@@ -1,19 +1,13 @@
use std::{env, fs::File, io::Read};
use strata_desktop_core::{gateway, hardware, node, planner, remote};
mod cli;
fn read_json<T: serde::de::DeserializeOwned>(path: &str) -> Result<T, Box<dyn std::error::Error>> {
let mut data = Vec::new();
File::open(path)?
.take(1024 * 1024 + 1)
.read_to_end(&mut data)?;
if data.len() > 1024 * 1024 {
return Err("input JSON exceeds 1 MiB".into());
}
Ok(serde_json::from_slice(&data)?)
}
use cli::read_json;
use std::env;
use strata_desktop_core::{gateway, hardware, planner, remote};
type Failure = Box<dyn std::error::Error>;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn main() -> Result<(), Failure> {
let args: Vec<_> = env::args().skip(1).collect();
if let [cmd, l, listen, n, address, t, token_env] = args.as_slice()
&& cmd == "node-proxy"
@@ -21,257 +15,72 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
&& n == "--node"
&& t == "--token-env"
{
let listen: std::net::SocketAddr = listen.parse()?;
if !listen.ip().is_loopback() {
return Err("proxy must bind loopback".into());
}
let token = std::env::var(token_env).map_err(|_| "missing node credential")?;
let proxy =
strata_desktop_core::node_proxy::Proxy::connect(address.parse()?, token).await?;
let listener = tokio::net::TcpListener::bind(listen).await?;
axum::serve(listener, proxy.router())
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
return Ok(());
return cli::proxy::run(listen, address, token_env).await;
}
if let [cmd, file] = args.as_slice()
&& cmd == "ssh-tunnel"
{
let stdio_lifetime = file == "--stdio-lifetime";
let config = if stdio_lifetime {
use std::io::BufRead;
let mut line = Vec::new();
std::io::stdin()
.lock()
.take(1024 * 1024 + 1)
.read_until(b'\n', &mut line)?;
if line.len() > 1024 * 1024 || line.last() != Some(&b'\n') {
return Err("invalid tunnel bootstrap size or framing".into());
}
serde_json::from_slice(&line)?
} else {
read_json(file)?
};
let tunnel = strata_desktop_core::ssh_tunnel::Tunnel::bind(&config).await?;
let (closed_tx, closed_rx) = tokio::sync::oneshot::channel();
if stdio_lifetime {
std::thread::spawn(move || {
let mut byte = [0];
while std::io::stdin().read(&mut byte).is_ok_and(|n| n > 0) {}
let _ = closed_tx.send(());
});
}
println!(
"{}",
serde_json::json!({"schema_version":1,"endpoint":format!("http://{}",tunnel.address()),"transport":"ssh","readiness":"requires_authenticated_node_handshake"})
);
use std::io::Write;
std::io::stdout().flush()?;
return tunnel
.serve(async move {
if stdio_lifetime {
tokio::select! { _ = closed_rx => {}, _ = tokio::signal::ctrl_c() => {} }
} else {
let _ = tokio::signal::ctrl_c().await;
}
})
.await
.map_err(Into::into);
return cli::tunnel::run(file).await;
}
if args.first().is_some_and(|s| s == "worker") {
return worker(&args[1..]).await;
return cli::worker::run(&args[1..]).await;
}
if args.first().is_some_and(|s| s == "node") {
return serve_node(&args[1..]).await;
return cli::node::serve(&args[1..]).await;
}
let value = match args.as_slice() {
[cmd, file] if cmd == "remote-install" => serde_json::to_value(
strata_desktop_core::remote_install::install(read_json(file)?).await?,
)?,
[cmd, file] if cmd == "remote-activate" => serde_json::to_value(
strata_desktop_core::remote_install::activate(read_json(file)?).await?,
)?,
[cmd, file] if cmd == "validate-worker" => {
let profile: strata_desktop_core::managed_worker::Profile = read_json(file)?;
if let Some(value) = run_command(&args).await? {
println!("{}", serde_json::to_string_pretty(&value)?);
}
Ok(())
}
const USAGE: &str = "usage: strata-desktop --help (hardware, plan, remote-inspect, gateway)";
/// The one-shot commands; `None` when the command printed its own output or has none.
async fn run_command(args: &[String]) -> Result<Option<serde_json::Value>, Failure> {
match args {
[cmd] => single_command(cmd).await,
[cmd, file] => file_command(cmd, file).await,
[cmd, file, flag, snapshot] if cmd == "plan" && flag == "--hardware" => Ok(Some(
serde_json::to_value(planner::plan(&read_json(snapshot)?, &read_json(file)?)?)?,
)),
_ => Err(USAGE.into()),
}
}
async fn single_command(cmd: &str) -> Result<Option<serde_json::Value>, Failure> {
match cmd {
"hardware" => Ok(Some(serde_json::to_value(hardware::inventory().await)?)),
"--help" | "help" => {
println!("{}", cli::HELP);
Ok(None)
}
_ => Err(USAGE.into()),
}
}
async fn file_command(cmd: &str, file: &str) -> Result<Option<serde_json::Value>, Failure> {
use strata_desktop_core::{managed_worker::Profile, remote_install};
let value = match cmd {
"remote-install" => serde_json::to_value(remote_install::install(read_json(file)?).await?)?,
"remote-activate" => {
serde_json::to_value(remote_install::activate(read_json(file)?).await?)?
}
"validate-worker" => {
let profile: Profile = read_json(file)?;
profile.validate()?;
return Ok(());
return Ok(None);
}
[cmd, file] if cmd == "remote-inspect" => {
serde_json::to_value(remote::inspect(&read_json(file)?).await?)?
}
[cmd, file] if cmd == "gateway" => {
"remote-inspect" => serde_json::to_value(remote::inspect(&read_json(file)?).await?)?,
"gateway" => {
gateway::serve(read_json(file)?).await?;
return Ok(());
return Ok(None);
}
[cmd] if cmd == "hardware" => serde_json::to_value(hardware::inventory().await)?,
[cmd, file] if cmd == "plan" => {
let r = read_json(file)?;
serde_json::to_value(planner::plan(&hardware::inventory().await, &r)?)?
}
[cmd, file, flag, snapshot] if cmd == "plan" && flag == "--hardware" => {
serde_json::to_value(planner::plan(&read_json(snapshot)?, &read_json(file)?)?)?
}
[cmd] if cmd == "--help" || cmd == "help" => {
println!(
"strata-desktop hardware\nstrata-desktop plan REQUIREMENTS.json [--hardware SNAPSHOT.json]\nstrata-desktop remote-inspect SSH_PROFILE.json\nstrata-desktop ssh-tunnel TUNNEL_PROFILE.json\nstrata-desktop remote-install INSTALL.json\nstrata-desktop remote-activate ACTIVATION.json\nstrata-desktop validate-worker WORKER.json\nstrata-desktop gateway POOL.json\nstrata-desktop node --listen 127.0.0.1:0 --token-env ENV [--pool POOL.json | --worker-profile FILE [--journal PRIVATE_PATH] | --stdio-lifetime]\nstrata-desktop node-proxy --listen 127.0.0.1:18765 --node 127.0.0.1:18766 --token-env ENV\nstrata-desktop worker --node 127.0.0.1:18766 --token-env ENV status|start UUID|stop UUID|operation UUID\nInventory and planning are read-only. Gateway serves configured loopback workers; it does not start or replace models."
);
return Ok(());
}
_ => {
return Err(
"usage: strata-desktop --help (hardware, plan, remote-inspect, gateway)".into(),
);
"plan" => {
let requirements = read_json(file)?;
serde_json::to_value(planner::plan(&hardware::inventory().await, &requirements)?)?
}
_ => return Err(USAGE.into()),
};
println!("{}", serde_json::to_string_pretty(&value)?);
Ok(())
}
async fn serve_node(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
use std::io::Write;
let (address, token_env, mode) = match args {
[a, address, t, token_env, rest @ ..] if a == "--listen" && t == "--token-env" => {
(address, token_env, rest)
}
_ => return Err(
"usage: node --listen LOOPBACK:PORT --token-env ENV [--pool FILE | --worker-profile FILE [--journal PRIVATE_PATH] | --stdio-lifetime]"
.into(),
),
};
let address: std::net::SocketAddr = address.parse()?;
if !address.ip().is_loopback() {
return Err("node must bind loopback".into());
}
if token_env.is_empty()
|| !token_env
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
{
return Err("invalid credential variable name".into());
}
let token = std::env::var(token_env).map_err(|_| "missing node credential")?;
let mut profile = None;
let mut journal = None;
let (gateway, stdio_lifetime) = match mode {
[p, file, j, path] if p == "--worker-profile" && j == "--journal" => {
profile = Some(read_json(file)?);
journal = Some(std::path::Path::new(path));
(None, false)
}
[p, file] if p == "--worker-profile" => {
profile = Some(read_json(file)?);
(None, false)
}
[] => (None, false),
[s] if s == "--stdio-lifetime" => (None, true),
[p, file] if p == "--pool" => (
Some(gateway::Gateway::with_token(
read_json(file)?,
token.clone(),
)?),
false,
),
_ => return Err("invalid node mode; stdio lifetime cannot own inference".into()),
};
let agent = if let Some(profile) = profile {
node::Agent::managed_journal(token, profile, journal)?
} else {
node::Agent::new(token, gateway)?
};
let listener = tokio::net::TcpListener::bind(address).await?;
println!(
"{}",
serde_json::json!({"schema_version":1,"endpoint":format!("http://{}",listener.local_addr()?)})
);
std::io::stdout().flush()?;
let (closed_tx, closed_rx) = tokio::sync::oneshot::channel();
if stdio_lifetime {
std::thread::spawn(move || {
let mut b = [0; 1];
while std::io::stdin().read(&mut b).is_ok_and(|n| n > 0) {}
let _ = closed_tx.send(());
});
}
agent
.serve(listener, async move {
if stdio_lifetime {
let _ = closed_rx.await;
} else {
let _ = tokio::signal::ctrl_c().await;
}
})
.await
}
async fn worker(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
use node::proto::*;
let [n, address, t, env, action, rest @ ..] = args else {
return Err("worker --node LOOPBACK:PORT --token-env ENV status|start UUID|stop UUID|operation UUID".into());
};
if n != "--node" || t != "--token-env" {
return Err("invalid worker options".into());
}
let token = std::env::var(env).map_err(|_| "missing node credential")?;
let mut client = node::connect(address.parse()?).await?;
let value = match (action.as_str(), rest) {
("status", []) => {
let s = client
.worker_status(worker_request(Empty {}, &token)?)
.await?
.into_inner();
serde_json::json!({"profile_id":s.profile_id,"model":s.model,"phase":s.phase,"pid":s.pid,"reason":s.reason})
}
("start" | "stop", [id]) => {
let epoch = client
.handshake(worker_request(
Hello {
protocol_version: 1,
},
&token,
)?)
.await?
.into_inner()
.agent_epoch;
let s = client
.control_worker(worker_request(
WorkerCommand {
operation_id: id.clone(),
expected_epoch: epoch,
action: if action == "start" { 1 } else { 2 },
drain_timeout_ms: if action == "stop" { 30000 } else { 0 },
},
&token,
)?)
.await?
.into_inner();
serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason})
}
("operation", [id]) => {
let s = client
.operation_status(worker_request(
OperationQuery {
operation_id: id.clone(),
},
&token,
)?)
.await?
.into_inner();
serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason})
}
_ => {
return Err(
"invalid worker action; supply a stable operation UUID for commands".into(),
);
}
};
println!("{}", serde_json::to_string(&value)?);
Ok(())
}
fn worker_request<T>(message: T, token: &str) -> Result<tonic::Request<T>, tonic::Status> {
let mut request = node::authorized(message, token)?;
request.set_timeout(std::time::Duration::from_secs(5));
Ok(request)
Ok(Some(value))
}
@@ -9,43 +9,67 @@ pub(super) fn default_capabilities() -> Vec<String> {
impl Profile {
pub fn validate(&self) -> Result<(), String> {
if self.schema_version != 1
|| self.id.is_empty()
|| self.id.len() > 128
|| !self
.id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|| self.capabilities.is_empty()
|| self.capabilities.len() > 16
|| !self.capabilities.iter().any(|c| c == "responses")
|| self.capabilities.iter().any(|c| {
![
"responses",
"tools",
"reasoning",
"structured_output",
"image",
"audio",
"file",
]
.contains(&c.as_str())
})
|| self.model.is_empty()
|| self.model.len() > 256
|| self.model.chars().any(char::is_control)
|| !self.executable.is_absolute()
|| !self.executable.is_file()
|| self.args.len() > 256
|| self.args.iter().any(|a| a.len() > 4096 || a.contains('\0'))
|| self.args.iter().map(String::len).sum::<usize>() > 32768
|| !self.endpoint.ip().is_loopback()
|| self.endpoint.port() < 1024
|| !(100..=3600000).contains(&self.startup_timeout_ms)
|| !self.identity_ok()
|| !self.capabilities_ok()
|| !self.model_ok()
|| !self.process_ok()
|| !self.endpoint_ok()
{
return Err("invalid managed worker profile".into());
}
Ok(())
}
fn identity_ok(&self) -> bool {
!self.id.is_empty()
&& self.id.len() <= 128
&& self
.id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
fn capabilities_ok(&self) -> bool {
const KNOWN: [&str; 7] = [
"responses",
"tools",
"reasoning",
"structured_output",
"image",
"audio",
"file",
];
!self.capabilities.is_empty()
&& self.capabilities.len() <= 16
&& self.capabilities.iter().any(|c| c == "responses")
&& self
.capabilities
.iter()
.all(|c| KNOWN.contains(&c.as_str()))
}
fn model_ok(&self) -> bool {
!self.model.is_empty()
&& self.model.len() <= 256
&& !self.model.chars().any(char::is_control)
}
fn process_ok(&self) -> bool {
self.executable.is_absolute()
&& self.executable.is_file()
&& self.args.len() <= 256
&& self
.args
.iter()
.all(|a| a.len() <= 4096 && !a.contains('\0'))
&& self.args.iter().map(String::len).sum::<usize>() <= 32768
}
fn endpoint_ok(&self) -> bool {
self.endpoint.ip().is_loopback()
&& self.endpoint.port() >= 1024
&& (100..=3600000).contains(&self.startup_timeout_ms)
}
pub fn gateway(&self, token: String) -> Result<Gateway, String> {
self.validate()?;
let gateway = Gateway::with_token(self.gateway_config(), token)?;
@@ -166,38 +190,12 @@ impl Manager {
.ok_or_else(|| Status::not_found("unknown operation for this epoch"))
}
pub fn submit(&self, mut c: WorkerCommand) -> Result<WorkerOperation, Status> {
c.operation_id = uuid::Uuid::parse_str(&c.operation_id)
.map_err(|_| Status::invalid_argument("operation UUID required"))?
.to_string();
if !(1..=2).contains(&c.action)
|| c.drain_timeout_ms > 30000
|| (c.action == 1 && c.drain_timeout_ms != 0)
|| c.expected_epoch.len() > 128
{
return Err(Status::invalid_argument(
"invalid worker action or drain timeout",
));
}
check_command(&mut c)?;
let mut records = self.0.records.lock().unwrap();
if let Some((old, result)) = records.entries.get(&c.operation_id) {
return if old.action == c.action && old.drain_timeout_ms == c.drain_timeout_ms {
Ok(result.clone())
} else {
Err(Status::already_exists(
"operation ID has different parameters",
))
};
}
if records.blocked {
return Err(Status::failed_precondition(
"journal reconciliation required",
));
}
if records.entries.len() >= 256 {
return Err(Status::resource_exhausted(
"operation history full; reconcile before new epoch",
));
if let Some(done) = replay(&records, &c)? {
return Ok(done);
}
check_capacity(&records)?;
let permit = self
.0
.tx
@@ -219,6 +217,49 @@ impl Manager {
Ok(result)
}
}
/// Normalizes the operation ID and refuses an unknown action or an out-of-range drain timeout.
fn check_command(c: &mut WorkerCommand) -> Result<(), Status> {
c.operation_id = uuid::Uuid::parse_str(&c.operation_id)
.map_err(|_| Status::invalid_argument("operation UUID required"))?
.to_string();
if !(1..=2).contains(&c.action)
|| c.drain_timeout_ms > 30000
|| (c.action == 1 && c.drain_timeout_ms != 0)
|| c.expected_epoch.len() > 128
{
return Err(Status::invalid_argument(
"invalid worker action or drain timeout",
));
}
Ok(())
}
/// The recorded outcome of a repeated operation ID; the same ID with other parameters is refused.
fn replay(records: &History, c: &WorkerCommand) -> Result<Option<WorkerOperation>, Status> {
let Some((old, result)) = records.entries.get(&c.operation_id) else {
return Ok(None);
};
if old.action == c.action && old.drain_timeout_ms == c.drain_timeout_ms {
Ok(Some(result.clone()))
} else {
Err(Status::already_exists(
"operation ID has different parameters",
))
}
}
/// A blocked journal or a full history takes no new operation.
fn check_capacity(records: &History) -> Result<(), Status> {
if records.blocked {
return Err(Status::failed_precondition(
"journal reconciliation required",
));
}
if records.entries.len() >= 256 {
return Err(Status::resource_exhausted(
"operation history full; reconcile before new epoch",
));
}
Ok(())
}
pub(super) fn state(tx: &watch::Sender<WorkerState>, phase: &str, pid: u32, reason: &str) {
tx.send_modify(|s| {
s.phase = phase.into();
+155 -73
View File
@@ -3,6 +3,69 @@
#[allow(unused_imports)]
use super::*;
/// Environment variables a managed worker inherits; nothing else is passed on.
const INHERITED_ENVIRONMENT: [&str; 11] = [
"PATH",
"HOME",
"USER",
"TMPDIR",
"TEMP",
"TMP",
"SystemRoot",
"WINDIR",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
"CUDA_VISIBLE_DEVICES",
];
/// Whether the owned child has already exited (`try_wait` failing is `wait_failed`).
fn exited(child: &mut Child) -> Result<bool, &'static str> {
Ok(child.try_wait().map_err(|_| "wait_failed")?.is_some())
}
fn worker_command(profile: &Profile, gateway: &Gateway) -> Command {
let mut command = Command::new(&profile.executable);
command.args(&profile.args).env_clear();
for key in INHERITED_ENVIRONMENT {
if let Some(value) = std::env::var_os(key) {
// Even a nonstandard token variable must not leak through the allowlist.
if !gateway.matches_credential(&value.to_string_lossy()) {
command.env(key, value);
}
}
}
command
.env("STRATA_WORKER_ENDPOINT", profile.endpoint.to_string())
.env("STRATA_WORKER_MODEL", &profile.model);
command
}
/// Polls until the worker is healthy and still alive, it exits, or the startup deadline passes.
async fn await_ready(
profile: &Profile,
gateway: &Gateway,
tx: &watch::Sender<WorkerState>,
child: &mut Option<Child>,
client: &reqwest::Client,
pid: u32,
) -> Result<(), &'static str> {
let deadline = tokio::time::Instant::now() + Duration::from_millis(profile.startup_timeout_ms);
while tokio::time::Instant::now() < deadline {
if exited(child.as_mut().unwrap())? {
*child = None;
return Err("worker_exited");
}
if healthy(client, profile).await && !exited(child.as_mut().unwrap())? {
gateway.set_managed_ready(true);
state(tx, "ready", pid, "");
return Ok(());
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
terminate(child).await?;
Err("startup_timeout")
}
pub(super) async fn start(
profile: &Profile,
gateway: &Gateway,
@@ -11,7 +74,7 @@ pub(super) async fn start(
client: &reqwest::Client,
) -> Result<(), &'static str> {
if let Some(c) = child.as_mut()
&& c.try_wait().map_err(|_| "wait_failed")?.is_some()
&& exited(c)?
{
*child = None;
}
@@ -30,32 +93,7 @@ pub(super) async fn start(
drop(listener);
gateway.clear_response_owners();
state(tx, "starting", 0, "");
let mut command = Command::new(&profile.executable);
command.args(&profile.args).env_clear();
for key in [
"PATH",
"HOME",
"USER",
"TMPDIR",
"TEMP",
"TMP",
"SystemRoot",
"WINDIR",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
"CUDA_VISIBLE_DEVICES",
] {
if let Some(value) = std::env::var_os(key) {
// Even a nonstandard token variable must not leak through the allowlist.
if !gateway.matches_credential(&value.to_string_lossy()) {
command.env(key, value);
}
}
}
command
.env("STRATA_WORKER_ENDPOINT", profile.endpoint.to_string())
.env("STRATA_WORKER_MODEL", &profile.model);
let process = command
let process = worker_command(profile, gateway)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
@@ -65,34 +103,7 @@ pub(super) async fn start(
let pid = process.id().unwrap_or(0);
*child = Some(process);
state(tx, "starting", pid, "");
let deadline = tokio::time::Instant::now() + Duration::from_millis(profile.startup_timeout_ms);
while tokio::time::Instant::now() < deadline {
if child
.as_mut()
.unwrap()
.try_wait()
.map_err(|_| "wait_failed")?
.is_some()
{
*child = None;
return Err("worker_exited");
}
if healthy(client, profile).await
&& child
.as_mut()
.unwrap()
.try_wait()
.map_err(|_| "wait_failed")?
.is_none()
{
gateway.set_managed_ready(true);
state(tx, "ready", pid, "");
return Ok(());
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
terminate(child).await?;
Err("startup_timeout")
await_ready(profile, gateway, tx, child, client, pid).await
}
pub(super) async fn stop(
gateway: &Gateway,
@@ -153,6 +164,81 @@ impl History {
Ok(())
}
}
/// The owner task's state: the profile it launches, the child it owns and the records it keeps.
struct Owner {
profile: Profile,
gateway: Gateway,
tx: watch::Sender<WorkerState>,
records: Records,
client: reqwest::Client,
child: Option<Child>,
}
impl Owner {
/// Runs one start or stop command, recording it before and after.
async fn command(&mut self, command: WorkerCommand) {
if self
.records
.lock()
.unwrap()
.update(&command, "running", "")
.is_err()
{
self.gateway.set_managed_ready(false);
return;
}
let result = if command.action == 1 {
let (profile, gateway) = (&self.profile, &self.gateway);
start(profile, gateway, &self.tx, &mut self.child, &self.client).await
} else {
stop(
&self.gateway,
&self.tx,
&mut self.child,
command.drain_timeout_ms,
)
.await
};
if let Err(reason) = result {
self.gateway.set_managed_ready(false);
let pid = self.child.as_ref().and_then(Child::id).unwrap_or(0);
state(&self.tx, "failed", pid, reason);
}
let status = if result.is_ok() {
"succeeded"
} else {
"failed"
};
let reason = result.err().unwrap_or("");
if self
.records
.lock()
.unwrap()
.update(&command, status, reason)
.is_err()
{
self.gateway.set_managed_ready(false);
}
}
/// Notices a child that exited, or could not be polled, between commands.
fn tick(&mut self) {
let Some(c) = self.child.as_mut() else { return };
match c.try_wait() {
Ok(Some(_)) => {
self.child = None;
self.gateway.set_managed_ready(false);
state(&self.tx, "failed", 0, "worker_exited");
}
Err(_) => {
self.gateway.set_managed_ready(false);
state(&self.tx, "failed", c.id().unwrap_or(0), "wait_failed");
}
Ok(None) => {}
}
}
}
pub(super) async fn run(
profile: Profile,
gateway: Gateway,
@@ -166,28 +252,24 @@ pub(super) async fn run(
.timeout(Duration::from_millis(500))
.build()
.expect("HTTP client");
let mut child: Option<Child> = None;
let mut owner = Owner {
profile,
gateway,
tx,
records,
client,
child: None,
};
let mut tick = tokio::time::interval(Duration::from_millis(200));
loop {
tokio::select! {
command=rx.recv()=>{
let Some(command)=command else{break};
if records.lock().unwrap().update(&command,"running","").is_err(){gateway.set_managed_ready(false);continue}
let result=if command.action==1 {start(&profile,&gateway,&tx,&mut child,&client).await}else{stop(&gateway,&tx,&mut child,command.drain_timeout_ms).await};
if let Err(reason)=result {gateway.set_managed_ready(false);state(&tx,"failed",child.as_ref().and_then(Child::id).unwrap_or(0),reason);}
if records.lock().unwrap().update(&command,if result.is_ok(){"succeeded"}else{"failed"},result.err().unwrap_or("")).is_err(){gateway.set_managed_ready(false);}
command = rx.recv() => {
let Some(command) = command else { break };
owner.command(command).await;
},
_=tick.tick()=>{
if let Some(c)=child.as_mut() {
match c.try_wait() {
Ok(Some(_))=>{child=None;gateway.set_managed_ready(false);state(&tx,"failed",0,"worker_exited");},
Err(_)=>{gateway.set_managed_ready(false);state(&tx,"failed",c.id().unwrap_or(0),"wait_failed");},
Ok(None)=>{}
}
}
}
_ = tick.tick() => owner.tick(),
}
}
gateway.set_managed_ready(false);
let _ = terminate(&mut child).await;
owner.gateway.set_managed_ready(false);
let _ = terminate(&mut owner.child).await;
}
+32 -114
View File
@@ -4,14 +4,15 @@ use crate::{
node::proto::{WorkerCommand, WorkerOperation},
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::{File, OpenOptions},
fs::File,
io::{Read, Write},
path::Path,
};
mod load;
const MAX_BYTES: u64 = 4 * 1024 * 1024;
pub(crate) type Entries = HashMap<String, (WorkerCommand, WorkerOperation)>;
pub(crate) struct Journal {
@@ -36,52 +37,11 @@ struct Entry {
}
impl Journal {
pub fn open(path: &Path, profile: &Profile) -> Result<(Self, Entries), String> {
if !path.is_absolute() {
return Err("journal path must be absolute".into());
}
let parent = path.parent().ok_or("journal parent required")?;
let parent_meta =
std::fs::symlink_metadata(parent).map_err(|_| "journal parent must exist")?;
if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
return Err("journal parent must be a real private directory".into());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if parent_meta.permissions().mode() & 0o077 != 0 {
return Err("journal directory must have mode 0700".into());
}
}
if let Ok(m) = std::fs::symlink_metadata(path)
&& (!m.is_file() || m.file_type().is_symlink())
{
return Err("journal must be a regular file".into());
}
let mut options = OpenOptions::new();
options.create(true).read(true).append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path).map_err(|_| "cannot open journal")?;
file.try_lock()
.map_err(|_| "journal already owned or locking unavailable")?;
let meta = file.metadata().map_err(|_| "cannot inspect journal")?;
#[cfg(unix)]
{
use std::os::unix::fs::{MetadataExt, PermissionsExt};
if meta.permissions().mode() & 0o077 != 0 || meta.nlink() != 1 {
return Err("journal must be private and not hardlinked".into());
}
}
if meta.len() > MAX_BYTES {
return Err("journal size limit".into());
}
let digest = Sha256::digest(serde_json::to_vec(profile).map_err(|_| "invalid profile")?)
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>();
let parent = load::check_parent(path)?;
load::check_existing(path)?;
let mut file = load::open_file(path)?;
let meta = load::lock_and_inspect(&file)?;
let digest = load::profile_digest(profile)?;
let mut text = String::new();
file.read_to_string(&mut text)
.map_err(|_| "unreadable journal")?;
@@ -90,79 +50,36 @@ impl Journal {
bytes: meta.len(),
};
if text.is_empty() {
journal.line(&Header {
version: 1,
profile_sha256: digest,
})?;
#[cfg(unix)]
File::open(parent)
.and_then(|f| f.sync_all())
.map_err(|_| "journal directory sync failed")?;
return Ok((journal, HashMap::new()));
}
if !text.ends_with('\n') {
return Err("incomplete journal; preserve for reconciliation".into());
}
let mut lines = text.lines();
let header: Header = serde_json::from_str(lines.next().ok_or("missing journal header")?)
.map_err(|_| "invalid journal header")?;
if header.version != 1 || header.profile_sha256 != digest {
return Err("journal profile/version mismatch".into());
}
let mut records: Entries = HashMap::new();
for line in lines {
let e: Entry = serde_json::from_str(line).map_err(|_| "invalid journal record")?;
if uuid::Uuid::parse_str(&e.id).is_err()
|| e.epoch.len() > 128
|| e.reason.len() > 256
|| !(1..=2).contains(&e.action)
|| e.grace > 30000
|| (e.action == 1 && e.grace != 0)
|| ![
"accepted",
"running",
"succeeded",
"failed",
"indeterminate",
]
.contains(&e.status.as_str())
{
return Err("invalid journal command".into());
}
let c = WorkerCommand {
operation_id: e.id.clone(),
action: e.action,
drain_timeout_ms: e.grace,
expected_epoch: e.epoch,
};
let r = WorkerOperation {
operation_id: e.id.clone(),
status: e.status,
reason: e.reason,
};
if let Some((old, previous)) = records.get(&e.id) {
if old != &c
|| !matches!(
(previous.status.as_str(), r.status.as_str()),
("accepted", "running" | "indeterminate")
| ("running", "succeeded" | "failed" | "indeterminate")
)
{
return Err("invalid journal transition".into());
}
} else if r.status != "accepted" || records.len() >= 256 {
return Err("invalid journal history".into());
}
records.insert(e.id, (c, r));
return journal.initialise(parent, digest);
}
let mut records = load::parse(&text, &digest)?;
journal.mark_restarted(&mut records)?;
Ok((journal, records))
}
/// A new journal: write the header and sync the directory.
fn initialise(mut self, parent: &Path, digest: String) -> Result<(Self, Entries), String> {
self.line(&Header {
version: 1,
profile_sha256: digest,
})?;
#[cfg(unix)]
File::open(parent)
.and_then(|f| f.sync_all())
.map_err(|_| "journal directory sync failed")?;
#[cfg(not(unix))]
let _ = parent;
Ok((self, HashMap::new()))
}
/// Commands that were in flight when the node stopped are recorded as indeterminate.
fn mark_restarted(&mut self, records: &mut Entries) -> Result<(), String> {
for (c, r) in records.values_mut() {
if r.status == "accepted" || r.status == "running" {
r.status = "indeterminate".into();
r.reason = "node_restarted".into();
journal.append(c, r)?;
self.append(c, r)?;
}
}
Ok((journal, records))
Ok(())
}
fn line(&mut self, value: &impl Serialize) -> Result<(), String> {
let mut bytes = serde_json::to_vec(value).map_err(|_| "journal encoding failed")?;
@@ -192,6 +109,7 @@ impl Journal {
#[cfg(test)]
mod tests {
use super::*;
use std::fs::OpenOptions;
struct Temp(std::path::PathBuf);
impl Temp {
fn new() -> Self {
+158
View File
@@ -0,0 +1,158 @@
//! The checks `Journal::open` runs, one per stage: path, file, header and records.
use super::{Entries, Entry, Header, MAX_BYTES};
use crate::{
managed_worker::Profile,
node::proto::{WorkerCommand, WorkerOperation},
};
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::{File, Metadata, OpenOptions},
path::Path,
};
const STATUSES: [&str; 5] = [
"accepted",
"running",
"succeeded",
"failed",
"indeterminate",
];
/// The parent must be a real private directory; returns it.
pub(super) fn check_parent(path: &Path) -> Result<&Path, String> {
if !path.is_absolute() {
return Err("journal path must be absolute".into());
}
let parent = path.parent().ok_or("journal parent required")?;
let parent_meta = std::fs::symlink_metadata(parent).map_err(|_| "journal parent must exist")?;
if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
return Err("journal parent must be a real private directory".into());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if parent_meta.permissions().mode() & 0o077 != 0 {
return Err("journal directory must have mode 0700".into());
}
}
Ok(parent)
}
/// An existing journal must be a regular file.
pub(super) fn check_existing(path: &Path) -> Result<(), String> {
if let Ok(m) = std::fs::symlink_metadata(path)
&& (!m.is_file() || m.file_type().is_symlink())
{
return Err("journal must be a regular file".into());
}
Ok(())
}
pub(super) fn open_file(path: &Path) -> Result<File, String> {
let mut options = OpenOptions::new();
options.create(true).read(true).append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
Ok(options.open(path).map_err(|_| "cannot open journal")?)
}
/// Takes the ownership lock, then checks mode, hard links and size.
pub(super) fn lock_and_inspect(file: &File) -> Result<Metadata, String> {
file.try_lock()
.map_err(|_| "journal already owned or locking unavailable")?;
let meta = file.metadata().map_err(|_| "cannot inspect journal")?;
#[cfg(unix)]
{
use std::os::unix::fs::{MetadataExt, PermissionsExt};
if meta.permissions().mode() & 0o077 != 0 || meta.nlink() != 1 {
return Err("journal must be private and not hardlinked".into());
}
}
if meta.len() > MAX_BYTES {
return Err("journal size limit".into());
}
Ok(meta)
}
pub(super) fn profile_digest(profile: &Profile) -> Result<String, String> {
let bytes = serde_json::to_vec(profile).map_err(|_| "invalid profile")?;
Ok(Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>())
}
/// Header and records of a non-empty journal, with every transition checked.
pub(super) fn parse(text: &str, digest: &str) -> Result<Entries, String> {
if !text.ends_with('\n') {
return Err("incomplete journal; preserve for reconciliation".into());
}
let mut lines = text.lines();
let header: Header = serde_json::from_str(lines.next().ok_or("missing journal header")?)
.map_err(|_| "invalid journal header")?;
if header.version != 1 || header.profile_sha256 != digest {
return Err("journal profile/version mismatch".into());
}
let mut records: Entries = HashMap::new();
for line in lines {
let e: Entry = serde_json::from_str(line).map_err(|_| "invalid journal record")?;
check_entry(&e)?;
let id = e.id.clone();
let pair = pair_of(e);
check_history(&records, &pair)?;
records.insert(id, pair);
}
Ok(records)
}
fn check_entry(e: &Entry) -> Result<(), String> {
if uuid::Uuid::parse_str(&e.id).is_err()
|| e.epoch.len() > 128
|| e.reason.len() > 256
|| !(1..=2).contains(&e.action)
|| e.grace > 30000
|| (e.action == 1 && e.grace != 0)
|| !STATUSES.contains(&e.status.as_str())
{
return Err("invalid journal command".into());
}
Ok(())
}
fn pair_of(e: Entry) -> (WorkerCommand, WorkerOperation) {
let c = WorkerCommand {
operation_id: e.id.clone(),
action: e.action,
drain_timeout_ms: e.grace,
expected_epoch: e.epoch,
};
let r = WorkerOperation {
operation_id: e.id,
status: e.status,
reason: e.reason,
};
(c, r)
}
/// A record repeats its command and only moves forward; a new id starts as accepted within the bound.
fn check_history(records: &Entries, pair: &(WorkerCommand, WorkerOperation)) -> Result<(), String> {
let (c, r) = pair;
if let Some((old, previous)) = records.get(&c.operation_id) {
if old != c
|| !matches!(
(previous.status.as_str(), r.status.as_str()),
("accepted", "running" | "indeterminate")
| ("running", "succeeded" | "failed" | "indeterminate")
)
{
return Err("invalid journal transition".into());
}
} else if r.status != "accepted" || records.len() >= 256 {
return Err("invalid journal history".into());
}
Ok(())
}
+119 -62
View File
@@ -1,4 +1,4 @@
use crate::hardware::{Hardware, MemoryKind};
use crate::hardware::{Accelerator, Hardware, MemoryKind};
use serde::{Deserialize, Serialize};
/// Runtime allocations supplied by a model/backend adapter, NOT archive size.
@@ -53,7 +53,8 @@ fn sum(values: &[u64]) -> Result<u64, String> {
})
}
pub fn plan(h: &Hardware, r: &Requirements) -> Result<Plan, String> {
/// Refuses unsupported schemas, empty requirements and memory figures that contradict themselves.
fn validate(h: &Hardware, r: &Requirements) -> Result<(), String> {
if h.schema_version != 1 || r.schema_version != 1 {
return Err("unsupported schema version".into());
}
@@ -71,6 +72,100 @@ pub fn plan(h: &Hardware, r: &Requirements) -> Result<Plan, String> {
return Err("available memory exceeds total".into());
}
}
Ok(())
}
/// Device and host weight bytes when `percent` of the weights go to the device.
fn split_weights(r: &Requirements, percent: u32) -> (u64, u64) {
let device_weights = ((u128::from(r.weights_bytes) * u128::from(percent)).div_ceil(100)) as u64;
let host_weights = if r.retains_host_weights {
r.weights_bytes
} else {
r.weights_bytes - device_weights
};
(device_weights, host_weights)
}
/// The sizes every placement of one requirement shares.
struct Sizing<'a> {
r: &'a Requirements,
runtime: u64,
cpu_peak: u64,
host_budget: Option<u64>,
}
impl Sizing<'_> {
/// The device-side budget of `g` after the reserve.
fn device_budget(&self, g: &Accelerator) -> Option<u64> {
let reserve = self.r.device_reserve_bytes;
g.memory.available_bytes.map(|n| n.saturating_sub(reserve))
}
/// Memory the device shares with the host: weights and runtime are counted ONCE in the host peak, and the
/// device ceiling is enforced as well.
fn shared(&self, g: &Accelerator) -> Result<Candidate, String> {
let r = self.r;
let retained = if r.retains_host_weights {
r.weights_bytes
} else {
0
};
let shared_peak = sum(&[self.cpu_peak, retained])?;
let mut c = candidate(
&g.id,
"shared",
100,
shared_peak,
sum(&[r.weights_bytes, self.runtime])?,
self.host_budget,
self.device_budget(g),
true,
);
if g.memory_kind == MemoryKind::Unknown {
c.fit = "unknown".into();
c.reasons.push("memory topology unknown".into());
}
Ok(c)
}
/// Dedicated device memory: the whole weights, or (when the backend allows it) a share of them, on the device.
fn dedicated(&self, g: &Accelerator, out: &mut Vec<Candidate>) -> Result<(), String> {
let r = self.r;
let splits: &[u32] = if r.allow_weight_offload {
&[100, 75, 50, 25]
} else {
&[100]
};
for &percent in splits {
let (device_weights, host_weights) = split_weights(r, percent);
// Conservative: reserve scratch on host too for upload/decode staging.
let host_peak = sum(&[host_weights, r.host_overhead_bytes, r.load_scratch_bytes])?;
let device_peak = sum(&[device_weights, self.runtime])?;
out.push(candidate(
&g.id,
if percent == 100 { "device" } else { "offload" },
percent,
host_peak,
device_peak,
self.host_budget,
self.device_budget(g),
true,
));
}
Ok(())
}
}
const PLAN_WARNINGS: [&str; 2] = [
"Memory fit does not establish model/backend compatibility, quality or speed.",
concat!(
"Requirements must describe runtime allocations; compressed file size is insufficient. ",
"Recheck available memory before load."
),
];
pub fn plan(h: &Hardware, r: &Requirements) -> Result<Plan, String> {
validate(h, r)?;
let kv = r
.kv_bytes_per_token_per_request
.checked_mul(r.context_tokens)
@@ -82,6 +177,12 @@ pub fn plan(h: &Hardware, r: &Requirements) -> Result<Plan, String> {
.available_bytes
.map(|n| n.saturating_sub(r.host_reserve_bytes));
let cpu_peak = sum(&[r.weights_bytes, runtime, r.host_overhead_bytes])?;
let sizing = Sizing {
r,
runtime,
cpu_peak,
host_budget,
};
let mut candidates = vec![candidate(
"cpu",
"host",
@@ -93,69 +194,22 @@ pub fn plan(h: &Hardware, r: &Requirements) -> Result<Plan, String> {
false,
)];
for g in &h.accelerators {
let device_budget = g
.memory
.available_bytes
.map(|n| n.saturating_sub(r.device_reserve_bytes));
if g.memory_kind != MemoryKind::Dedicated {
// Shared weights/runtime are counted ONCE in host_peak; also enforce device ceiling.
let shared_peak = sum(&[
cpu_peak,
if r.retains_host_weights {
r.weights_bytes
} else {
0
},
])?;
let mut c = candidate(
&g.id,
"shared",
100,
shared_peak,
sum(&[r.weights_bytes, runtime])?,
host_budget,
device_budget,
true,
);
if g.memory_kind == MemoryKind::Unknown {
c.fit = "unknown".into();
c.reasons.push("memory topology unknown".into());
}
candidates.push(c);
continue;
}
let splits: &[u32] = if r.allow_weight_offload {
&[100, 75, 50, 25]
candidates.push(sizing.shared(g)?);
} else {
&[100]
};
for &percent in splits {
let device_weights =
((u128::from(r.weights_bytes) * u128::from(percent)).div_ceil(100)) as u64;
let host_weights = if r.retains_host_weights {
r.weights_bytes
} else {
r.weights_bytes - device_weights
};
// Conservative: reserve scratch on host too for upload/decode staging.
let host_peak = sum(&[host_weights, r.host_overhead_bytes, r.load_scratch_bytes])?;
let device_peak = sum(&[device_weights, runtime])?;
candidates.push(candidate(
&g.id,
if percent == 100 { "device" } else { "offload" },
percent,
host_peak,
device_peak,
host_budget,
device_budget,
true,
));
sizing.dedicated(g, &mut candidates)?;
}
}
Ok(Plan {schema_version:1, model:r.model.clone(),context_tokens:r.context_tokens,
concurrent_requests:r.concurrent_requests,evidence:"estimated",execution_compatibility:"not_validated",
warnings: vec!["Memory fit does not establish model/backend compatibility, quality or speed.".into(),
"Requirements must describe runtime allocations; compressed file size is insufficient. Recheck available memory before load.".into()], candidates})
Ok(Plan {
schema_version: 1,
model: r.model.clone(),
context_tokens: r.context_tokens,
concurrent_requests: r.concurrent_requests,
evidence: "estimated",
execution_compatibility: "not_validated",
warnings: PLAN_WARNINGS.iter().map(|w| w.to_string()).collect(),
candidates,
})
}
/// How a placement fits: too small beats unknown, which beats fitting the estimate.
@@ -209,7 +263,10 @@ fn candidate(
needs_device: bool,
) -> Candidate {
let (reasons, unknown, insufficient) = budget_findings(
[("host", host_peak, host_budget), ("device", device_peak, device_budget)],
[
("host", host_peak, host_budget),
("device", device_peak, device_budget),
],
needs_device,
);
Candidate {
+65 -176
View File
@@ -1,16 +1,16 @@
//! OpenSSH transport preflight. Does not install or start anything on the host.
use crate::hardware::{Hardware, Memory, parse_nvidia};
use crate::hardware::Hardware;
use inventory::parse;
use serde::{Deserialize, Serialize};
use std::{
path::Path,
process::Stdio,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use std::{process::Stdio, time::Duration};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
process::Command,
process::{Child, ChildStderr, ChildStdin, ChildStdout, Command},
};
mod inventory;
mod profile;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SshProfile {
@@ -33,45 +33,11 @@ pub struct RemoteInventory {
}
impl SshProfile {
pub fn arguments(&self) -> Result<Vec<String>, String> {
let ident = |s: &str| {
!s.is_empty()
&& s.len() <= 128
&& s.as_bytes()[0].is_ascii_alphanumeric()
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
};
if self.schema_version != 1
|| !ident(&self.id)
|| self.host.is_empty()
|| self.host.len() > 253
|| !self.host.as_bytes()[0].is_ascii_alphanumeric()
|| !self
.host
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._-:".contains(&b))
|| self.user.as_ref().is_some_and(|s| !ident(s))
|| self.port == Some(0)
{
return Err("invalid SSH profile".into());
}
let mut args = vec![
"-T",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"ForwardAgent=no",
"-o",
"ClearAllForwardings=yes",
"-o",
"PermitLocalCommand=no",
"-o",
"ConnectTimeout=8",
]
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>();
self.validate()?;
let mut args = profile::BASE_OPTIONS
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>();
if let Some(port) = self.port {
args.extend(["-p".into(), port.to_string()]);
}
@@ -79,17 +45,22 @@ impl SshProfile {
args.extend(["-l".into(), user.clone()]);
}
if let Some(path) = &self.identity_file {
if !Path::new(path).is_absolute()
|| path.len() > 4096
|| path.chars().any(char::is_control)
{
return Err("SSH identity must be an absolute key-file reference".into());
}
args.extend(["-i".into(), path.clone()]);
args.extend(profile::identity_args(path)?);
}
args.extend(["--".into(), self.host.clone(), "sh".into(), "-s".into()]);
Ok(args)
}
fn validate(&self) -> Result<(), String> {
if self.schema_version != 1
|| !profile::valid_ident(&self.id)
|| !profile::valid_host(&self.host)
|| self.user.as_ref().is_some_and(|s| !profile::valid_ident(s))
|| self.port == Some(0)
{
return Err("invalid SSH profile".into());
}
Ok(())
}
}
// Static stdin only: no profile values interpolated into this remote shell program.
const PROBE: &str = r#"export LC_ALL=C
@@ -135,38 +106,10 @@ async fn inspect_with_program(
.kill_on_drop(true)
.spawn()
.map_err(|_| "OpenSSH is unavailable")?;
let mut input = child.stdin.take().ok_or("SSH stdin missing")?;
let input = child.stdin.take().ok_or("SSH stdin missing")?;
let output = child.stdout.take().ok_or("SSH stdout missing")?;
let error = child.stderr.take().ok_or("SSH stderr missing")?;
let run = async {
let write = async move {
input
.write_all(PROBE.as_bytes())
.await
.map_err(|_| "SSH input failed".to_string())?;
drop(input); // Close the pipe: remote `sh -s` must receive EOF.
Ok::<(), String>(())
};
let (_, output, error) = tokio::try_join!(write, bounded(output), bounded(error))?;
let status = child.wait().await.map_err(|_| "SSH wait failed")?;
if !status.success() {
let error = String::from_utf8_lossy(&error);
return Err(if error.contains("Host key verification failed")
|| error.contains("REMOTE HOST IDENTIFICATION HAS CHANGED")
{
"SSH host identity is not trusted or has changed"
} else if error.contains("Permission denied") {
"SSH authentication failed"
} else {
"SSH preflight failed; verify connection and host configuration"
}
.to_string());
}
parse(
profile,
&String::from_utf8(output).map_err(|_| "SSH output is not UTF-8")?,
)
};
let run = run_probe(profile, &mut child, (input, output, error));
match tokio::time::timeout(limit, run).await {
Ok(Ok(result)) => Ok(result),
failure => {
@@ -178,100 +121,40 @@ async fn inspect_with_program(
}
}
}
fn parse(profile: &SshProfile, data: &str) -> Result<RemoteInventory, String> {
let mut fields = std::collections::HashMap::new();
let mut gpus = Vec::new();
for line in data.lines() {
let Some((key, value)) = line.split_once('\t') else {
return Err("unexpected SSH probe output".into());
};
if key == "gpu" {
gpus.push(value);
} else if fields.insert(key, value).is_some() {
return Err("duplicate SSH probe field".into());
}
/// Sends the probe, collects both output streams and the exit status, then reads the inventory.
async fn run_probe(
profile: &SshProfile,
child: &mut Child,
(input, output, error): (ChildStdin, ChildStdout, ChildStderr),
) -> Result<RemoteInventory, String> {
let (_, output, error) = tokio::try_join!(send_probe(input), bounded(output), bounded(error))?;
let status = child.wait().await.map_err(|_| "SSH wait failed")?;
if !status.success() {
return Err(failure_reason(&String::from_utf8_lossy(&error)).to_string());
}
if fields.get("os") != Some(&"Linux") {
return Err("remote worker preflight currently supports Linux only".into());
}
if fields.get("end") != Some(&"ok") {
return Err("incomplete SSH probe".into());
}
let kib = |key: &str| {
fields
.get(key)
.and_then(|s| s.parse::<u64>().ok())
.and_then(|n| n.checked_mul(1024))
};
let memory = Memory {
total_bytes: kib("total_kib"),
available_bytes: kib("available_kib"),
};
if memory.total_bytes.is_none_or(|n| n == 0)
|| matches!((memory.total_bytes,memory.available_bytes),(Some(t),Some(a)) if a>t)
parse(
profile,
&String::from_utf8(output).map_err(|_| "SSH output is not UTF-8")?,
)
}
async fn send_probe(mut input: ChildStdin) -> Result<(), String> {
input
.write_all(PROBE.as_bytes())
.await
.map_err(|_| "SSH input failed".to_string())?;
drop(input); // Close the pipe: remote `sh -s` must receive EOF.
Ok(())
}
fn failure_reason(error: &str) -> &'static str {
if error.contains("Host key verification failed")
|| error.contains("REMOTE HOST IDENTIFICATION HAS CHANGED")
{
return Err("invalid remote RAM inventory".into());
"SSH host identity is not trusted or has changed"
} else if error.contains("Permission denied") {
"SSH authentication failed"
} else {
"SSH preflight failed; verify connection and host configuration"
}
let architecture = match fields.get("arch").copied() {
Some("x86_64") => "x86_64",
Some("aarch64" | "arm64") => "aarch64",
_ => return Err("unsupported remote CPU architecture".into()),
};
let cpus = fields
.get("cpus")
.and_then(|s| s.parse::<usize>().ok())
.filter(|n| *n > 0)
.ok_or("invalid remote CPU count")?;
let flags = fields
.get("features")
.copied()
.unwrap_or("")
.split_whitespace()
.collect::<std::collections::HashSet<_>>();
let cpu_features = [
("avx2", "avx2"),
("avx512f", "avx512f"),
("fma", "fma"),
("asimd", "neon"),
("asimddp", "dotprod"),
]
.into_iter()
.filter(|(flag, _)| flags.contains(flag))
.map(|(_, name)| name.to_owned())
.collect();
let mut warnings =
vec!["NPU and inference-provider support require a separate capability check.".into()];
let accelerators = match parse_nvidia(&gpus.join("\n")) {
Ok(g) => g,
Err(e) => {
warnings.push(e);
vec![]
}
};
if accelerators.is_empty() {
warnings.push("No NVIDIA inventory; other accelerators are not probed yet.".into());
}
Ok(RemoteInventory {
schema_version: 1,
node_id: profile.id.clone(),
transport: "ssh",
home_disk_available_bytes: kib("disk_available_kib"),
hardware: Hardware {
schema_version: 1,
sampled_at_unix_ms: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|t| t.as_millis() as u64)
.unwrap_or(0),
os: "linux".into(),
architecture: architecture.into(),
cpu_name: fields.get("cpu").copied().unwrap_or("unknown").into(),
logical_cpus: cpus,
cpu_features,
memory,
accelerators,
warnings,
},
})
}
#[cfg(test)]
mod tests {
@@ -317,7 +200,10 @@ mod tests {
}
#[test]
fn parses_server_memory_and_unknown_accelerators() {
let data = "os\tLinux\narch\tx86_64\ncpus\t8\ncpu\tFixture CPU\nfeatures\tavx2 fma\ntotal_kib\t33554432\navailable_kib\t16777216\ndisk_available_kib\t1024\nend\tok\n";
let data = concat!(
"os\tLinux\narch\tx86_64\ncpus\t8\ncpu\tFixture CPU\nfeatures\tavx2 fma\n",
"total_kib\t33554432\navailable_kib\t16777216\ndisk_available_kib\t1024\nend\tok\n"
);
let r = parse(&profile(), data).unwrap();
assert_eq!(
r.hardware.memory.available_bytes,
@@ -356,7 +242,10 @@ mod tests {
}
let path =
Temp(std::env::temp_dir().join(format!("strata-ssh-test-{}", std::process::id())));
let script = "#!/bin/sh\ncat >/dev/null\nprintf 'os\\tLinux\\narch\\tx86_64\\ncpus\\t1\\ntotal_kib\\t1024\\nend\\tok\\n'\n";
let script = concat!(
"#!/bin/sh\ncat >/dev/null\n",
"printf 'os\\tLinux\\narch\\tx86_64\\ncpus\\t1\\ntotal_kib\\t1024\\nend\\tok\\n'\n"
);
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
+138
View File
@@ -0,0 +1,138 @@
//! The probe reply of a remote host, read field by field into a hardware inventory.
use super::{RemoteInventory, SshProfile};
use crate::hardware::{Accelerator, Hardware, Memory, parse_nvidia};
use std::{
collections::{HashMap, HashSet},
time::{SystemTime, UNIX_EPOCH},
};
type Fields<'a> = HashMap<&'a str, &'a str>;
pub(super) fn parse(profile: &SshProfile, data: &str) -> Result<RemoteInventory, String> {
let (fields, gpus) = read_fields(data)?;
if fields.get("os") != Some(&"Linux") {
return Err("remote worker preflight currently supports Linux only".into());
}
if fields.get("end") != Some(&"ok") {
return Err("incomplete SSH probe".into());
}
let memory = memory(&fields)?;
let architecture = architecture(&fields)?;
let cpus = cpu_count(&fields)?;
let (accelerators, warnings) = accelerators(&gpus);
Ok(RemoteInventory {
schema_version: 1,
node_id: profile.id.clone(),
transport: "ssh",
home_disk_available_bytes: kib(&fields, "disk_available_kib"),
hardware: Hardware {
schema_version: 1,
sampled_at_unix_ms: sampled_at_unix_ms(),
os: "linux".into(),
architecture: architecture.into(),
cpu_name: fields.get("cpu").copied().unwrap_or("unknown").into(),
logical_cpus: cpus,
cpu_features: cpu_features(&fields),
memory,
accelerators,
warnings,
},
})
}
/// Splits the tab-separated lines into unique fields and the repeated `gpu` rows.
fn read_fields(data: &str) -> Result<(Fields<'_>, Vec<&str>), String> {
let mut fields = HashMap::new();
let mut gpus = Vec::new();
for line in data.lines() {
let Some((key, value)) = line.split_once('\t') else {
return Err("unexpected SSH probe output".into());
};
if key == "gpu" {
gpus.push(value);
} else if fields.insert(key, value).is_some() {
return Err("duplicate SSH probe field".into());
}
}
Ok((fields, gpus))
}
fn kib(fields: &Fields, key: &str) -> Option<u64> {
fields
.get(key)
.and_then(|s| s.parse::<u64>().ok())
.and_then(|n| n.checked_mul(1024))
}
fn memory(fields: &Fields) -> Result<Memory, String> {
let memory = Memory {
total_bytes: kib(fields, "total_kib"),
available_bytes: kib(fields, "available_kib"),
};
if memory.total_bytes.is_none_or(|n| n == 0)
|| matches!((memory.total_bytes,memory.available_bytes),(Some(t),Some(a)) if a>t)
{
return Err("invalid remote RAM inventory".into());
}
Ok(memory)
}
fn architecture(fields: &Fields) -> Result<&'static str, String> {
match fields.get("arch").copied() {
Some("x86_64") => Ok("x86_64"),
Some("aarch64" | "arm64") => Ok("aarch64"),
_ => Err("unsupported remote CPU architecture".into()),
}
}
fn cpu_count(fields: &Fields) -> Result<usize, String> {
Ok(fields
.get("cpus")
.and_then(|s| s.parse::<usize>().ok())
.filter(|n| *n > 0)
.ok_or("invalid remote CPU count")?)
}
fn cpu_features(fields: &Fields) -> Vec<String> {
let flags = fields
.get("features")
.copied()
.unwrap_or("")
.split_whitespace()
.collect::<HashSet<_>>();
[
("avx2", "avx2"),
("avx512f", "avx512f"),
("fma", "fma"),
("asimd", "neon"),
("asimddp", "dotprod"),
]
.into_iter()
.filter(|(flag, _)| flags.contains(flag))
.map(|(_, name)| name.to_owned())
.collect()
}
/// NVIDIA devices plus the warnings that go with the inventory.
fn accelerators(gpus: &[&str]) -> (Vec<Accelerator>, Vec<String>) {
let mut warnings =
vec!["NPU and inference-provider support require a separate capability check.".into()];
let accelerators = match parse_nvidia(&gpus.join("\n")) {
Ok(g) => g,
Err(e) => {
warnings.push(e);
vec![]
}
};
if accelerators.is_empty() {
warnings.push("No NVIDIA inventory; other accelerators are not probed yet.".into());
}
(accelerators, warnings)
}
fn sampled_at_unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|t| t.as_millis() as u64)
.unwrap_or(0)
}
+44
View File
@@ -0,0 +1,44 @@
//! Validation of the SSH profile fields and the fixed option list of every `ssh` command line.
use std::path::Path;
/// Options of every connection: batch mode, pinned host keys and no forwarding.
pub(super) const BASE_OPTIONS: [&str; 13] = [
"-T",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"ForwardAgent=no",
"-o",
"ClearAllForwardings=yes",
"-o",
"PermitLocalCommand=no",
"-o",
"ConnectTimeout=8",
];
pub(super) fn valid_ident(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 128
&& s.as_bytes()[0].is_ascii_alphanumeric()
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
}
pub(super) fn valid_host(host: &str) -> bool {
!host.is_empty()
&& host.len() <= 253
&& host.as_bytes()[0].is_ascii_alphanumeric()
&& host
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._-:".contains(&b))
}
/// `-i <path>` for an identity file reference, which must be an absolute path without control characters.
pub(super) fn identity_args(path: &str) -> Result<[String; 2], String> {
if !Path::new(path).is_absolute() || path.len() > 4096 || path.chars().any(char::is_control) {
return Err("SSH identity must be an absolute key-file reference".into());
}
Ok(["-i".into(), path.to_owned()])
}
+32 -121
View File
@@ -6,14 +6,10 @@ use std::{
fs::File,
io::{Read, Seek, SeekFrom},
path::{Path, PathBuf},
process::Stdio,
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
process::Command,
};
mod exec;
const SCRIPT: &str = include_str!("remote_install.sh");
const MAX_BINARY: u64 = 256 * 1024 * 1024;
const MAX_PROFILE: u64 = 1024 * 1024;
@@ -112,6 +108,19 @@ fn prepare(config: &Install) -> Result<Prepared, String> {
.metadata()
.map_err(|_| "cannot inspect runtime")?
.len();
verify_runtime(&mut binary, size, &config.runtime_sha256)?;
binary
.seek(SeekFrom::Start(0))
.map_err(|_| "cannot rewind runtime")?;
let profile = read_profile(&config.worker_profile)?;
Ok(Prepared {
binary,
size,
profile,
})
}
/// Streams the runtime once: bounded, of the expected size and with the pinned SHA-256.
fn verify_runtime(binary: &mut File, size: u64, pin: &str) -> Result<(), String> {
let mut digest = Sha256::new();
let mut buf = [0u8; 65536];
let mut count = 0;
@@ -126,14 +135,14 @@ fn prepare(config: &Install) -> Result<Prepared, String> {
}
digest.update(&buf[..n]);
}
if count != size || to_hex(&digest.finalize()) != config.runtime_sha256 {
if count != size || to_hex(&digest.finalize()) != pin {
return Err("runtime SHA-256 mismatch".into());
}
binary
.seek(SeekFrom::Start(0))
.map_err(|_| "cannot rewind runtime")?;
Ok(())
}
fn read_profile(path: &Path) -> Result<Vec<u8>, String> {
let mut profile = Vec::new();
regular(&config.worker_profile, MAX_PROFILE)?
regular(path, MAX_PROFILE)?
.take(MAX_PROFILE + 1)
.read_to_end(&mut profile)
.map_err(|_| "cannot read worker profile")?;
@@ -142,11 +151,7 @@ fn prepare(config: &Install) -> Result<Prepared, String> {
}
// Paths belong to the target OS: validate semantic/path constraints there.
serde_json::from_slice::<Profile>(&profile).map_err(|_| "invalid worker profile JSON")?;
Ok(Prepared {
binary,
size,
profile,
})
Ok(profile)
}
pub async fn install(config: Install) -> Result<Receipt, String> {
validate(
@@ -206,112 +211,18 @@ async fn execute(
prepared: Option<Prepared>,
) -> Result<Receipt, String> {
let (os, arch) = target.platform()?;
let release = hex_hash(format!("v1:{os}:{arch}:{binary_hash}:{profile_hash}").as_bytes());
let action = if prepared.is_some() {
"install"
} else {
"activate"
};
let (size, profile_size) = prepared
.as_ref()
.map(|p| (p.size, p.profile.len()))
.unwrap_or_default();
let remote_command = format!(
"sh -c {} strata-install {action} {} {os} {arch} {binary_hash} {profile_hash} {release} {size} {profile_size}",
quote(SCRIPT),
target.slot
);
let mut args = target.ssh.arguments()?;
args.truncate(args.len() - 4);
for option in [
"ControlMaster=no",
"ControlPath=none",
"ControlPersist=no",
"ForwardX11=no",
"ServerAliveInterval=10",
"ServerAliveCountMax=3",
] {
args.extend(["-o".into(), option.into()]);
}
args.extend(["--".into(), target.ssh.host.clone(), remote_command]);
let mut child = Command::new("ssh")
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| "cannot start SSH installer")?;
let mut stdin = child.stdin.take().ok_or("missing SSH stdin")?;
let stdout = child.stdout.take().ok_or("missing SSH stdout")?;
let result = tokio::time::timeout(Duration::from_secs(180), async {
let upload = async move {
if let Some(p) = prepared {
let mut file = tokio::fs::File::from_std(p.binary).take(p.size);
let copied = tokio::io::copy(&mut file, &mut stdin).await?;
if copied != p.size {
return Err(std::io::Error::other("runtime truncated during transfer"));
}
stdin.write_all(&p.profile).await?;
}
stdin.shutdown().await
};
let receive = async move {
let mut data = Vec::new();
stdout.take(8193).read_to_end(&mut data).await?;
if data.len() > 8192 {
return Err(std::io::Error::other("installer output too large"));
}
Ok(data)
};
tokio::join!(upload, receive, child.wait())
})
.await;
let (bytes, status) = match result {
Ok((uploaded, Ok(bytes), Ok(status))) if uploaded.is_ok() || !status.success() => {
(bytes, status)
}
_ => {
let _ = child.kill().await;
let _ = child.wait().await;
return Err("SSH installation interrupted; activation outcome unknown, retry with the same pins".into());
}
};
if !status.success() {
for code in [
"target_os",
"target_arch",
"directory_symlink",
"directory_create",
"directory_type",
"directory_permissions",
"runtime_type",
"profile_type",
"runtime_digest",
"profile_digest",
"profile_validation",
"slot_locked",
"marker_symlink",
"marker_type",
"stale_marker",
"disk_probe",
"disk_capacity",
"upload_size",
"runtime_size",
"profile_size",
"release_missing",
] {
if bytes == format!("error:{code}\n").as_bytes() {
return Err(format!("remote installation rejected: {code}"));
}
}
}
let outcome = match (status.success(), bytes.as_slice()) {
(true, b"ok:installed\n") => "installed",
(true, b"ok:reused\n") => "reused",
(true, b"ok:activated\n") => "activated",
_ => return Err("remote installation failed; inspect target permissions, capacity, platform and worker profile; activation may require reconciliation".into()),
let release = exec::release(os, arch, binary_hash, profile_hash);
let pins = exec::Pins {
os,
arch,
binary_hash,
profile_hash,
release: &release,
};
let remote_command = exec::remote_command(target, &pins, prepared.as_ref());
let args = exec::ssh_args(target, remote_command)?;
let (bytes, status) = exec::run(args, prepared).await?;
let outcome = exec::outcome(status.success(), &bytes)?;
Ok(Receipt {
schema_version: 1,
slot: target.slot.clone(),
+164
View File
@@ -0,0 +1,164 @@
//! The SSH leg of an installation: command line, upload, reply and its classification.
use super::{Prepared, SCRIPT, Target, hex_hash, quote};
use std::{process::ExitStatus, process::Stdio, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
process::{ChildStdin, ChildStdout, Command},
};
const SSH_OPTIONS: [&str; 6] = [
"ControlMaster=no",
"ControlPath=none",
"ControlPersist=no",
"ForwardX11=no",
"ServerAliveInterval=10",
"ServerAliveCountMax=3",
];
/// Refusals the remote script reports as `error:<code>`.
const REJECTIONS: &[&str] = &[
"target_os",
"target_arch",
"directory_symlink",
"directory_create",
"directory_type",
"directory_permissions",
"runtime_type",
"profile_type",
"runtime_digest",
"profile_digest",
"profile_validation",
"slot_locked",
"marker_symlink",
"marker_type",
"stale_marker",
"disk_probe",
"disk_capacity",
"upload_size",
"runtime_size",
"profile_size",
"release_missing",
];
const INTERRUPTED: &str = concat!(
"SSH installation interrupted; ",
"activation outcome unknown, retry with the same pins"
);
const FAILED: &str = concat!(
"remote installation failed; inspect target permissions, capacity, platform and worker profile; ",
"activation may require reconciliation"
);
/// The release id pinned by platform, runtime and profile.
pub(super) fn release(os: &str, arch: &str, binary_hash: &str, profile_hash: &str) -> String {
hex_hash(format!("v1:{os}:{arch}:{binary_hash}:{profile_hash}").as_bytes())
}
pub(super) struct Pins<'a> {
pub os: &'a str,
pub arch: &'a str,
pub binary_hash: &'a str,
pub profile_hash: &'a str,
pub release: &'a str,
}
/// The `sh -c` line the remote end runs.
pub(super) fn remote_command(target: &Target, pins: &Pins, prepared: Option<&Prepared>) -> String {
let Pins {
os,
arch,
binary_hash,
profile_hash,
release,
} = pins;
let action = if prepared.is_some() {
"install"
} else {
"activate"
};
let (size, profile_size) = prepared
.map(|p| (p.size, p.profile.len()))
.unwrap_or_default();
format!(
"sh -c {} strata-install {action} {} {os} {arch} {binary_hash} {profile_hash} {release} {size} {profile_size}",
quote(SCRIPT),
target.slot
)
}
pub(super) fn ssh_args(target: &Target, remote_command: String) -> Result<Vec<String>, String> {
let mut args = target.ssh.arguments()?;
args.truncate(args.len() - 4);
for option in SSH_OPTIONS {
args.extend(["-o".into(), option.into()]);
}
args.extend(["--".into(), target.ssh.host.clone(), remote_command]);
Ok(args)
}
async fn upload(mut stdin: ChildStdin, prepared: Option<Prepared>) -> std::io::Result<()> {
if let Some(p) = prepared {
let mut file = tokio::fs::File::from_std(p.binary).take(p.size);
let copied = tokio::io::copy(&mut file, &mut stdin).await?;
if copied != p.size {
return Err(std::io::Error::other("runtime truncated during transfer"));
}
stdin.write_all(&p.profile).await?;
}
stdin.shutdown().await
}
async fn receive(stdout: ChildStdout) -> std::io::Result<Vec<u8>> {
let mut data = Vec::new();
stdout.take(8193).read_to_end(&mut data).await?;
if data.len() > 8192 {
return Err(std::io::Error::other("installer output too large"));
}
Ok(data)
}
/// Runs `ssh`, streams the artifacts and returns the installer's reply with its exit status.
pub(super) async fn run(
args: Vec<String>,
prepared: Option<Prepared>,
) -> Result<(Vec<u8>, ExitStatus), String> {
let mut child = Command::new("ssh")
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| "cannot start SSH installer")?;
let stdin = child.stdin.take().ok_or("missing SSH stdin")?;
let stdout = child.stdout.take().ok_or("missing SSH stdout")?;
let result = tokio::time::timeout(Duration::from_secs(180), async {
tokio::join!(upload(stdin, prepared), receive(stdout), child.wait())
})
.await;
match result {
Ok((uploaded, Ok(bytes), Ok(status))) if uploaded.is_ok() || !status.success() => {
Ok((bytes, status))
}
_ => {
let _ = child.kill().await;
let _ = child.wait().await;
Err(INTERRUPTED.into())
}
}
}
/// What the installer did, or why the remote end refused.
pub(super) fn outcome(success: bool, bytes: &[u8]) -> Result<&'static str, String> {
if !success {
for code in REJECTIONS {
if bytes == format!("error:{code}\n").as_bytes() {
return Err(format!("remote installation rejected: {code}"));
}
}
}
match (success, bytes) {
(true, b"ok:installed\n") => Ok("installed"),
(true, b"ok:reused\n") => Ok("reused"),
(true, b"ok:activated\n") => Ok("activated"),
_ => Err(FAILED.into()),
}
}
@@ -1,47 +1,100 @@
//! Moved out of the parent module by STRA-338: fn buffered_tool_generation, fn validated_tool_generation, fn tool_responses.
//! Moved out of the parent module by STRA-338: fn buffered_tool_generation, fn validated_tool_generation,
//! fn tool_responses.
#[allow(unused_imports)]
use super::*;
/// What a buffered tool generation yields: the validated segments, the summed usage and the finish reason.
pub(super) type ToolOutcome = Result<
(
Vec<crate::runtime_tools::ValidatedSegment>,
proto::Usage,
String,
),
&'static str,
>;
pub(super) async fn buffered_tool_generation(
mut stream: RuntimeGeneration,
) -> Result<(String, proto::Usage, String), &'static str> {
let mut text = String::new();
loop {
let frame = tokio::time::timeout(Duration::from_secs(3600), stream.message())
.await
.map_err(|_| "runtime_interrupted")?
.map_err(|_| "runtime_protocol_failed")?
.ok_or("runtime_missing_terminal")?;
match frame.payload.ok_or("runtime_protocol_failed")? {
match next_tool_payload(&mut stream).await? {
proto::generation_frame::Payload::Accepted(_) => {}
proto::generation_frame::Payload::Text(delta) => {
if delta.text.len() > (8 * 1024 * 1024_usize).saturating_sub(text.len()) {
return Err("tool_output_limit");
}
text.push_str(&delta.text);
append_tool_text(&mut text, &delta.text)?
}
proto::generation_frame::Payload::Usage(_) => {}
proto::generation_frame::Payload::Tool(_) => return Err("runtime_protocol_failed"),
proto::generation_frame::Payload::Terminal(terminal) => {
// RuntimeGeneration verifies actual HTTP2 EOF before returning
// this terminal. Unknown accepted transport is never retried.
if terminal.state != 1 {
return Err("runtime_generation_failed");
}
if !matches!(terminal.reason.as_str(), "stop" | "length") {
return Err("runtime_protocol_failed");
}
return Ok((
text,
terminal.usage.ok_or("runtime_protocol_failed")?,
terminal.reason,
));
return finish_tool_terminal(text, terminal);
}
}
}
}
async fn next_tool_payload(
stream: &mut RuntimeGeneration,
) -> Result<proto::generation_frame::Payload, &'static str> {
let frame = tokio::time::timeout(Duration::from_secs(3600), stream.message())
.await
.map_err(|_| "runtime_interrupted")?
.map_err(|_| "runtime_protocol_failed")?
.ok_or("runtime_missing_terminal")?;
frame.payload.ok_or("runtime_protocol_failed")
}
fn append_tool_text(text: &mut String, delta: &str) -> Result<(), &'static str> {
if delta.len() > (8 * 1024 * 1024_usize).saturating_sub(text.len()) {
return Err("tool_output_limit");
}
text.push_str(delta);
Ok(())
}
fn finish_tool_terminal(
text: String,
terminal: proto::Terminal,
) -> Result<(String, proto::Usage, String), &'static str> {
// RuntimeGeneration verifies actual HTTP2 EOF before returning
// this terminal. Unknown accepted transport is never retried.
if terminal.state != 1 {
return Err("runtime_generation_failed");
}
if !matches!(terminal.reason.as_str(), "stop" | "length") {
return Err("runtime_protocol_failed");
}
Ok((
text,
terminal.usage.ok_or("runtime_protocol_failed")?,
terminal.reason,
))
}
/// Adds one attempt's usage to the running total; any inconsistency or overflow is a protocol failure.
fn add_usage(total: &mut proto::Usage, usage: &proto::Usage) -> Result<(), &'static str> {
if usage.reused_input_tokens > usage.input_tokens {
return Err("runtime_protocol_failed");
}
total.input_tokens = total
.input_tokens
.checked_add(usage.input_tokens)
.ok_or("runtime_protocol_failed")?;
total.output_tokens = total
.output_tokens
.checked_add(usage.output_tokens)
.ok_or("runtime_protocol_failed")?;
total.reused_input_tokens = total
.reused_input_tokens
.checked_add(usage.reused_input_tokens)
.ok_or("runtime_protocol_failed")?;
total
.input_tokens
.checked_add(total.output_tokens)
.ok_or("runtime_protocol_failed")?;
Ok(())
}
pub(super) async fn validated_tool_generation(
registry: Registry,
index: usize,
@@ -49,145 +102,163 @@ pub(super) async fn validated_tool_generation(
initial_request: proto::GenerateRequest,
initial_stream: RuntimeGeneration,
mode_identity_digest: String,
) -> Result<
(
Vec<crate::runtime_tools::ValidatedSegment>,
proto::Usage,
String,
),
&'static str,
> {
) -> ToolOutcome {
let mut stream = initial_stream;
let mut actual_usage = proto::Usage::default();
for attempt in 0..2 {
let (raw, usage, reason) = buffered_tool_generation(stream).await?;
if usage.reused_input_tokens > usage.input_tokens {
return Err("runtime_protocol_failed");
}
actual_usage.input_tokens = actual_usage
.input_tokens
.checked_add(usage.input_tokens)
.ok_or("runtime_protocol_failed")?;
actual_usage.output_tokens = actual_usage
.output_tokens
.checked_add(usage.output_tokens)
.ok_or("runtime_protocol_failed")?;
actual_usage.reused_input_tokens = actual_usage
.reused_input_tokens
.checked_add(usage.reused_input_tokens)
.ok_or("runtime_protocol_failed")?;
actual_usage
.input_tokens
.checked_add(actual_usage.output_tokens)
.ok_or("runtime_protocol_failed")?;
add_usage(&mut actual_usage, &usage)?;
if let Ok(segments) = plan.policy.parse_output(&raw) {
return Ok((segments, actual_usage, reason));
}
if attempt != 0 {
return Err("tool_retry_exhausted");
}
// The previous operation completed and EOF was verified; none of its
// text/calls was published. This is a new model attempt, not a replay
// of an uncertain accepted request or any external tool action.
let (mut client, snapshot) = registry.observe(index).await.ok_or("runtime_interrupted")?;
let loaded = snapshot
.loaded
.filter(|_| snapshot.model_ready)
.ok_or("runtime_interrupted")?;
if snapshot.epoch != initial_request.expected_epoch
|| loaded.handle != initial_request.handle
|| loaded.mode_identity_digest != mode_identity_digest
{
return Err("runtime_interrupted");
}
let mut request = initial_request.clone();
request.request_id = uuid::Uuid::new_v4().to_string();
stream = accepted(&mut client, request)
.await
.map_err(|_| "runtime_interrupted")?;
stream = retry_stream(&registry, index, &initial_request, &mode_identity_digest).await?;
}
Err("tool_retry_exhausted")
}
/// The previous operation completed and EOF was verified; none of its text/calls was published. This is a new
/// model attempt, not a replay of an uncertain accepted request or any external tool action.
async fn retry_stream(
registry: &Registry,
index: usize,
initial_request: &proto::GenerateRequest,
mode_identity_digest: &str,
) -> Result<RuntimeGeneration, &'static str> {
let (mut client, snapshot) = registry.observe(index).await.ok_or("runtime_interrupted")?;
let loaded = snapshot
.loaded
.filter(|_| snapshot.model_ready)
.ok_or("runtime_interrupted")?;
if snapshot.epoch != initial_request.expected_epoch
|| loaded.handle != initial_request.handle
|| loaded.mode_identity_digest != mode_identity_digest
{
return Err("runtime_interrupted");
}
let mut request = initial_request.clone();
request.request_id = uuid::Uuid::new_v4().to_string();
accepted(&mut client, request)
.await
.map_err(|_| "runtime_interrupted")
}
/// A tool request that the runtime accepted: the request as sent, its stream and the mode the model was loaded in.
struct ToolDispatch {
request: proto::GenerateRequest,
stream: RuntimeGeneration,
mode_identity_digest: String,
}
async fn dispatch_tool_request(
registry: &Registry,
index: usize,
plan: &crate::runtime_tools::ToolPlan,
) -> Result<ToolDispatch, Response> {
let (mut client, epoch, loaded) = ready_member(registry, index).await?;
let mut request = proto::GenerateRequest {
request_id: uuid::Uuid::new_v4().to_string(),
expected_epoch: epoch,
handle: loaded.handle,
prompt: plan.prompt.clone(),
max_output_tokens: plan.max_output_tokens,
..Default::default()
};
crate::runtime_sampling::apply(&mut request, &plan.sampling);
match accepted(&mut client, request.clone()).await {
Ok(stream) => Ok(ToolDispatch {
request,
stream,
mode_identity_digest: loaded.mode_identity_digest,
}),
Err(_) => Err(error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed")),
}
}
pub(super) async fn tool_responses(registry: Registry, index: usize, value: Value) -> Response {
let plan = match crate::runtime_tools::prepare(&value) {
Ok(plan) => plan,
Err(code) => return error(StatusCode::BAD_REQUEST, code),
};
let Some((mut client, snapshot)) = registry.observe(index).await else {
return error(StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable");
let dispatch = match dispatch_tool_request(&registry, index, &plan).await {
Ok(dispatch) => dispatch,
Err(response) => return response,
};
let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else {
return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready");
};
let request_id = uuid::Uuid::new_v4().to_string();
let mut request = proto::GenerateRequest {
request_id: request_id.clone(),
expected_epoch: snapshot.epoch,
handle: loaded.handle,
prompt: plan.prompt.clone(),
max_output_tokens: plan.max_output_tokens,
..Default::default()
};
crate::runtime_sampling::apply(&mut request, &plan.sampling);
let stream = match accepted(&mut client, request.clone()).await {
Ok(stream) => stream,
Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"),
};
let mut publisher = crate::runtime_tool_response::ToolResponse::new(
format!("resp_{}", request_id.replace('-', "")),
let publisher = crate::runtime_tool_response::ToolResponse::new(
format!("resp_{}", dispatch.request.request_id.replace('-', "")),
registry.0.peers[index].config.id.clone(),
);
let completion = validated_tool_generation(
registry,
index,
plan,
let ToolDispatch {
request,
stream,
loaded.mode_identity_digest,
);
mode_identity_digest,
} = dispatch;
let completion =
validated_tool_generation(registry, index, plan, request, stream, mode_identity_digest);
if value.get("stream") == Some(&Value::Bool(true)) {
let output = async_stream::stream! {
for event in publisher.beginning() { yield Ok::<Bytes, std::io::Error>(event); }
tokio::pin!(completion);
let mut keepalive = tokio::time::interval(Duration::from_secs(15));
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
result = &mut completion => {
let events = match result {
Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) {
Ok((events, _)) => events,
Err(_) => publisher.failed("runtime_tool_output_invalid").0,
},
Err(code) => publisher.failed(code).0,
};
for event in events { yield Ok(event); }
break;
}
_ = keepalive.tick() => yield Ok(Bytes::from_static(b": keepalive\n\n")),
}
}
};
let mut response = Body::from_stream(output).into_response();
response
.headers_mut()
.insert("content-type", "text/event-stream".parse().unwrap());
response
.headers_mut()
.insert("cache-control", "no-store".parse().unwrap());
response
tool_event_stream(publisher, completion)
} else {
match completion.await {
Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) {
Ok((_, body)) => Json(body).into_response(),
Err(_) => (
StatusCode::BAD_GATEWAY,
Json(publisher.failed("runtime_tool_output_invalid").1),
)
.into_response(),
},
Err(code) => (StatusCode::BAD_GATEWAY, Json(publisher.failed(code).1)).into_response(),
tool_json(publisher, completion).await
}
}
/// The events that close a tool response: the completed one, or the failure the publisher reports.
fn tool_events(
publisher: &mut crate::runtime_tool_response::ToolResponse,
result: ToolOutcome,
) -> Vec<Bytes> {
match result {
Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) {
Ok((events, _)) => events,
Err(_) => publisher.failed("runtime_tool_output_invalid").0,
},
Err(code) => publisher.failed(code).0,
}
}
fn tool_event_stream<F>(
mut publisher: crate::runtime_tool_response::ToolResponse,
completion: F,
) -> Response
where
F: std::future::Future<Output = ToolOutcome> + Send + 'static,
{
let output = async_stream::stream! {
for event in publisher.beginning() { yield Ok::<Bytes, std::io::Error>(event); }
tokio::pin!(completion);
let mut keepalive = tokio::time::interval(Duration::from_secs(15));
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
result = &mut completion => {
for event in tool_events(&mut publisher, result) { yield Ok(event); }
break;
}
_ = keepalive.tick() => yield Ok(Bytes::from_static(b": keepalive\n\n")),
}
}
};
event_stream_response(Body::from_stream(output))
}
async fn tool_json<F>(
mut publisher: crate::runtime_tool_response::ToolResponse,
completion: F,
) -> Response
where
F: std::future::Future<Output = ToolOutcome>,
{
match completion.await {
Ok((segments, usage, reason)) => match publisher.complete(segments, &usage, &reason) {
Ok((_, body)) => Json(body).into_response(),
Err(_) => (
StatusCode::BAD_GATEWAY,
Json(publisher.failed("runtime_tool_output_invalid").1),
)
.into_response(),
},
Err(code) => (StatusCode::BAD_GATEWAY, Json(publisher.failed(code).1)).into_response(),
}
}
+90 -43
View File
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn credential, impl Config, impl Registry, fn control, fn control_peer, fn operation_value.
//! Moved out of the parent module by STRA-338: fn credential, impl Config, impl Registry, fn control,
//! fn control_peer, fn operation_value.
#[allow(unused_imports)]
use super::*;
@@ -33,6 +34,11 @@ impl Config {
credential(&self.token_env)
}
pub fn validate(&self) -> Result<(), String> {
self.check_shape()?;
let ids = self.check_members()?;
self.check_pool(&ids)
}
fn check_shape(&self) -> Result<(), String> {
if self.schema_version != 1
|| !self.listen.ip().is_loopback()
|| self.listen.port() == 0
@@ -41,27 +47,27 @@ impl Config {
{
return Err("invalid_daemon_configuration".into());
}
Ok(())
}
fn check_members(&self) -> Result<HashSet<&String>, String> {
let mut ids = HashSet::new();
for m in &self.runtimes {
let digest = m
.artifact_digest
.strip_prefix("sha256:")
.ok_or("invalid_model_digest")?;
if m.id.is_empty()
|| m.id.len() > 128
|| !m
.id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
if !id_syntax_valid(&m.id)
|| !ids.insert(&m.id)
|| !m.address.ip().is_loopback()
|| m.address.port() == 0
|| digest.len() != 64
|| !digest.bytes().all(|b| b.is_ascii_hexdigit())
|| !digest_valid(digest)
{
return Err("invalid_runtime_member".into());
}
}
Ok(ids)
}
fn check_pool(&self, ids: &HashSet<&String>) -> Result<(), String> {
if let Some(pool) = &self.http_pool
&& (pool.listen != self.listen
|| pool.deployments.iter().any(|d| ids.contains(&d.id))
@@ -72,6 +78,16 @@ impl Config {
Ok(())
}
}
fn id_syntax_valid(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 128
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
}
fn digest_valid(digest: &str) -> bool {
digest.len() == 64 && digest.bytes().all(|b| b.is_ascii_hexdigit())
}
impl Registry {
pub fn new(config: Config) -> Result<Self, String> {
config.validate()?;
@@ -115,30 +131,7 @@ impl Registry {
if state.blocked {
return None;
}
let result = async {
let mut client = match &state.client {
Some(c) => c.clone(),
None => RuntimeClient::connect(peer.config.address, peer.token.clone()).await?,
};
let snap = client.snapshot().await?;
if let Some(prior) = &state.snapshot
&& prior.epoch == snap.epoch
&& prior.sequence > snap.sequence
{
return Err(tonic::Status::data_loss("snapshot_regression"));
}
if let Some(loaded) = &snap.loaded
&& loaded
.descriptor
.as_ref()
.is_none_or(|d| d.artifact_digest != peer.config.artifact_digest)
{
return Err(tonic::Status::data_loss("runtime_model_identity_mismatch"));
}
Ok((client, snap))
}
.await;
match result {
match fetch_snapshot(peer, &state).await {
Ok((client, snap)) => {
state.client = Some(client.clone());
state.snapshot = Some(snap.clone());
@@ -147,14 +140,7 @@ impl Registry {
Err(e) => {
state.client = None;
state.snapshot = None;
state.blocked = matches!(
e.code(),
tonic::Code::Unauthenticated
| tonic::Code::PermissionDenied
| tonic::Code::DataLoss
| tonic::Code::FailedPrecondition
| tonic::Code::InvalidArgument
);
state.blocked = blocks_member(e.code());
None
}
}
@@ -204,7 +190,68 @@ pub(super) fn operation_value(
result: Result<proto::OperationResult, tonic::Status>,
) -> Response {
match result {
Ok(v)=>Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":v.state,"reason":v.reason,"loaded_handle":v.loaded.map(|v|v.handle)})).into_response(),
Err(_)=>(StatusCode::BAD_GATEWAY,Json(json!({"operation_id":c.operation_id,"epoch":c.epoch,"state":"outcome_unknown","error":{"type":"runtime_command_failed"}}))).into_response()
Ok(v) => Json(json!({
"operation_id":c.operation_id,
"epoch":c.epoch,
"state":v.state,
"reason":v.reason,
"loaded_handle":v.loaded.map(|v|v.handle)
}))
.into_response(),
Err(_) => (
StatusCode::BAD_GATEWAY,
Json(json!({
"operation_id":c.operation_id,
"epoch":c.epoch,
"state":"outcome_unknown",
"error":{"type":"runtime_command_failed"}
})),
)
.into_response(),
}
}
/// Connects (or reuses the connection) and reads the member's snapshot, refusing a regression or another model.
async fn fetch_snapshot(
peer: &Peer,
state: &MemberState,
) -> Result<(RuntimeClient, proto::Snapshot), tonic::Status> {
let mut client = match &state.client {
Some(c) => c.clone(),
None => RuntimeClient::connect(peer.config.address, peer.token.clone()).await?,
};
let snap = client.snapshot().await?;
check_snapshot(peer, state, &snap)?;
Ok((client, snap))
}
fn check_snapshot(
peer: &Peer,
state: &MemberState,
snap: &proto::Snapshot,
) -> Result<(), tonic::Status> {
if let Some(prior) = &state.snapshot
&& prior.epoch == snap.epoch
&& prior.sequence > snap.sequence
{
return Err(tonic::Status::data_loss("snapshot_regression"));
}
if let Some(loaded) = &snap.loaded
&& loaded
.descriptor
.as_ref()
.is_none_or(|d| d.artifact_digest != peer.config.artifact_digest)
{
return Err(tonic::Status::data_loss("runtime_model_identity_mismatch"));
}
Ok(())
}
/// A failure that needs the operator (credentials, identity, configuration) blocks the member until restart.
fn blocks_member(code: tonic::Code) -> bool {
matches!(
code,
tonic::Code::Unauthenticated
| tonic::Code::PermissionDenied
| tonic::Code::DataLoss
| tonic::Code::FailedPrecondition
| tonic::Code::InvalidArgument
)
}
+156 -94
View File
@@ -14,7 +14,28 @@ pub(super) async fn load(State(r): State<Registry>, h: HeaderMap, body: Bytes) -
if c.handle.is_some() {
return error(StatusCode::BAD_REQUEST, "unexpected_handle");
}
let mode = match (c.mode.as_deref(), c.profile_id.as_deref()) {
let Some(mode) = explicit_mode(&c) else {
return error(StatusCode::BAD_REQUEST, "invalid_explicit_mode");
};
let (mut client, _) = match control_peer(&r, &c).await {
Ok(p) => p,
Err((code, e)) => return error(code, e),
};
let model = pinned_descriptor();
if r.0
.peers
.iter()
.find(|p| p.config.id == c.model)
.is_none_or(|p| p.config.artifact_digest != model.artifact_digest)
{
return error(StatusCode::BAD_REQUEST, "unsupported_model_identity");
}
let result = client.load(load_request(&c, model, mode)).await;
operation_value(&c, result)
}
/// The inference mode a load command names explicitly; `None` for any combination that is not allowed.
fn explicit_mode(c: &Control) -> Option<proto::inference_mode::Selection> {
Some(match (c.mode.as_deref(), c.profile_id.as_deref()) {
(Some("native"), None) => proto::inference_mode::Selection::Native(proto::NativeMode {}),
(Some("kar-ple"), Some(id)) if !id.is_empty() && id.len() <= 128 => {
proto::inference_mode::Selection::KarPle(proto::KarPleMode {
@@ -26,42 +47,36 @@ pub(super) async fn load(State(r): State<Registry>, h: HeaderMap, body: Bytes) -
profile_id: id.to_owned(),
})
}
_ => return error(StatusCode::BAD_REQUEST, "invalid_explicit_mode"),
};
let (mut client, _) = match control_peer(&r, &c).await {
Ok(p) => p,
Err((code, e)) => return error(code, e),
};
_ => return None,
})
}
fn pinned_descriptor() -> proto::ModelDescriptor {
let d = leleka_runtime::backend::pinned_model_descriptor();
if r.0
.peers
.iter()
.find(|p| p.config.id == c.model)
.is_none_or(|p| p.config.artifact_digest != d.artifact_digest)
{
return error(StatusCode::BAD_REQUEST, "unsupported_model_identity");
proto::ModelDescriptor {
family: d.family,
architecture: d.architecture,
artifact_digest: d.artifact_digest,
weight_format: d.weight_format,
}
let result = client
.load(proto::LoadRequest {
operation_id: c.operation_id.clone(),
expected_epoch: c.epoch.clone(),
model: Some(proto::ModelDescriptor {
family: d.family,
architecture: d.architecture,
artifact_digest: d.artifact_digest,
weight_format: d.weight_format,
}
fn load_request(
c: &Control,
model: proto::ModelDescriptor,
mode: proto::inference_mode::Selection,
) -> proto::LoadRequest {
proto::LoadRequest {
operation_id: c.operation_id.clone(),
expected_epoch: c.epoch.clone(),
model: Some(model),
config: Some(proto::LoadConfig {
version: 1,
mode: Some(proto::InferenceMode {
selection: Some(mode),
}),
config: Some(proto::LoadConfig {
version: 1,
mode: Some(proto::InferenceMode {
selection: Some(mode),
}),
gpu_memory_limit_bytes: None,
allow_experimental: matches!(c.mode.as_deref(), Some("kar-ple" | "mtp")),
}),
})
.await;
operation_value(&c, result)
gpu_memory_limit_bytes: None,
allow_experimental: matches!(c.mode.as_deref(), Some("kar-ple" | "mtp")),
}),
}
}
pub(super) async fn unload(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Response {
if !r.authorized(&h) {
@@ -133,7 +148,13 @@ pub(super) async fn models(State(r): State<Registry>, h: HeaderMap) -> Response
&& snap.model_ready
&& let Some(loaded) = snap.loaded
{
data.push(json!({"id":r.0.peers[i].config.id,"object":"model","owned_by":"leleka-runtime","artifact_digest":r.0.peers[i].config.artifact_digest,"mode_identity_digest":loaded.mode_identity_digest}));
data.push(json!({
"id":r.0.peers[i].config.id,
"object":"model",
"owned_by":"leleka-runtime",
"artifact_digest":r.0.peers[i].config.artifact_digest,
"mode_identity_digest":loaded.mode_identity_digest
}));
}
}
Json(json!({"object":"list","data":data})).into_response()
@@ -146,26 +167,60 @@ pub(super) async fn status(State(r): State<Registry>, h: HeaderMap) -> Response
r.refresh().await;
for p in &r.0.peers {
let s = p.state.lock().await;
states.push(json!({"id":p.config.id,"connected":s.snapshot.is_some(),"epoch":s.snapshot.as_ref().map(|v|&v.epoch),"loaded_handle":s.snapshot.as_ref().and_then(|v|v.loaded.as_ref()).map(|v|&v.handle),"model_ready":s.snapshot.as_ref().is_some_and(|v|v.model_ready),"configuration_action_required":s.blocked}));
states.push(json!({
"id":p.config.id,
"connected":s.snapshot.is_some(),
"epoch":s.snapshot.as_ref().map(|v|&v.epoch),
"loaded_handle":s.snapshot.as_ref().and_then(|v|v.loaded.as_ref()).map(|v|&v.handle),
"model_ready":s.snapshot.as_ref().is_some_and(|v|v.model_ready),
"configuration_action_required":s.blocked
}));
}
Json(json!({"schema_version":1,"runtimes":states})).into_response()
}
type Owned = Vec<(Role, String)>;
pub(super) fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static str> {
let o = v.as_object().ok_or("invalid_json")?;
for (key, value) in o {
match key.as_str() {
"model" | "input" | "instructions" | "stream" | "max_output_tokens" => {}
key if leleka_serving_policy::fixed::SAMPLING_KEYS.contains(&key) => {}
"store" if value == &Value::Bool(false) => {}
"tools" if value.as_array().is_some_and(Vec::is_empty) => {}
"text" if value == &json!({"format":{"type":"text"}}) => {}
_ => return Err("unsupported_request_field"),
}
}
check_request_fields(o)?;
if o.get("stream").is_some_and(|v| !v.is_boolean()) {
return Err("invalid_stream");
}
let sampling = crate::runtime_sampling::from_json(o)?;
let cap = output_cap(o)?;
let prompt = render_prompt(&collect_messages(o)?)?;
Ok((prompt, cap as u32, sampling))
}
fn collect_messages(o: &serde_json::Map<String, Value>) -> Result<Owned, &'static str> {
let mut owned = Vec::new();
if let Some(s) = o.get("instructions") {
owned.push((
Role::System,
s.as_str().ok_or("invalid_instructions")?.to_owned(),
));
}
push_input(o.get("input").ok_or("input_required")?, &mut owned)?;
Ok(owned)
}
fn check_request_fields(o: &serde_json::Map<String, Value>) -> Result<(), &'static str> {
for (key, value) in o {
if !field_allowed(key, value) {
return Err("unsupported_request_field");
}
}
Ok(())
}
fn field_allowed(key: &str, value: &Value) -> bool {
match key {
"model" | "input" | "instructions" | "stream" | "max_output_tokens" => true,
key if leleka_serving_policy::fixed::SAMPLING_KEYS.contains(&key) => true,
"store" => value == &Value::Bool(false),
"tools" => value.as_array().is_some_and(Vec::is_empty),
"text" => value == &json!({"format":{"type":"text"}}),
_ => false,
}
}
fn output_cap(o: &serde_json::Map<String, Value>) -> Result<u64, &'static str> {
let cap = o
.get("max_output_tokens")
.map(|v| v.as_u64().ok_or("invalid_output_limit"))
@@ -174,60 +229,67 @@ pub(super) fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static st
if !(1..=4096).contains(&cap) {
return Err("invalid_output_limit");
}
let mut owned = Vec::new();
if let Some(s) = o.get("instructions") {
owned.push((
Role::System,
s.as_str().ok_or("invalid_instructions")?.to_owned(),
));
}
match o.get("input").ok_or("input_required")? {
Ok(cap)
}
fn push_input(input: &Value, owned: &mut Owned) -> Result<(), &'static str> {
match input {
Value::String(s) => owned.push((Role::User, s.clone())),
Value::Array(items) if !items.is_empty() && items.len() <= 1024 => {
for item in items {
let fields = item.as_object().ok_or("invalid_message")?;
if fields
.keys()
.any(|k| !matches!(k.as_str(), "type" | "role" | "content"))
|| fields.get("type").is_some_and(|t| t != "message")
{
return Err("unsupported_input_item");
}
let role = match item.get("role").and_then(Value::as_str) {
Some("system") => Role::System,
Some("developer") => Role::Developer,
Some("user") => Role::User,
Some("assistant") => Role::Assistant,
_ => return Err("invalid_role"),
};
let content = match item.get("content").ok_or("content_required")? {
Value::String(s) => s.clone(),
Value::Array(parts) => {
let mut s = String::new();
for part in parts {
if !matches!(
part.get("type").and_then(Value::as_str),
Some("input_text" | "output_text")
) || part.as_object().is_none_or(|m| {
m.keys().any(|k| !matches!(k.as_str(), "type" | "text"))
}) {
return Err("unsupported_content");
}
s.push_str(
part.get("text")
.and_then(Value::as_str)
.ok_or("invalid_text")?,
);
}
s
}
_ => return Err("invalid_content"),
};
owned.push((role, content));
owned.push(input_item(item)?);
}
}
_ => return Err("invalid_input"),
}
Ok(())
}
fn input_item(item: &Value) -> Result<(Role, String), &'static str> {
let fields = item.as_object().ok_or("invalid_message")?;
if fields
.keys()
.any(|k| !matches!(k.as_str(), "type" | "role" | "content"))
|| fields.get("type").is_some_and(|t| t != "message")
{
return Err("unsupported_input_item");
}
let role = item_role(item)?;
let content = match item.get("content").ok_or("content_required")? {
Value::String(s) => s.clone(),
Value::Array(parts) => join_parts(parts)?,
_ => return Err("invalid_content"),
};
Ok((role, content))
}
fn item_role(item: &Value) -> Result<Role, &'static str> {
Ok(match item.get("role").and_then(Value::as_str) {
Some("system") => Role::System,
Some("developer") => Role::Developer,
Some("user") => Role::User,
Some("assistant") => Role::Assistant,
_ => return Err("invalid_role"),
})
}
fn join_parts(parts: &[Value]) -> Result<String, &'static str> {
let mut s = String::new();
for part in parts {
if !matches!(
part.get("type").and_then(Value::as_str),
Some("input_text" | "output_text")
) || part
.as_object()
.is_none_or(|m| m.keys().any(|k| !matches!(k.as_str(), "type" | "text")))
{
return Err("unsupported_content");
}
s.push_str(
part.get("text")
.and_then(Value::as_str)
.ok_or("invalid_text")?,
);
}
Ok(s)
}
fn render_prompt(owned: &Owned) -> Result<String, &'static str> {
let messages = owned
.iter()
.map(|(role, content)| Message {
@@ -242,5 +304,5 @@ pub(super) fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static st
if prompt.len() > 1024 * 1024 {
return Err("prompt_limit");
}
Ok((prompt, cap as u32, sampling))
Ok(prompt)
}
+221 -104
View File
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn response_value, impl Trace, fn accepted, fn responses, fn needs_tool_adapter.
//! Moved out of the parent module by STRA-338: fn response_value, impl Trace, fn accepted, fn responses,
//! fn needs_tool_adapter.
#[allow(unused_imports)]
use super::*;
@@ -10,15 +11,49 @@ pub(super) fn response_value(
status: &str,
usage: &proto::Usage,
) -> Value {
json!({"id":id,"object":"response","created_at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0,|v|v.as_secs()),"model":model,"status":status,"output":[{"id":format!("msg_{id}"),"type":"message","role":"assistant","status":status,"content":[{"type":"output_text","text":text,"annotations":[]}]}],"usage":{"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}},"error":null,"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}})
let created_at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |v| v.as_secs());
json!({
"id":id, "object":"response", "created_at":created_at,
"model":model, "status":status,
"output":[{
"id":format!("msg_{id}"),
"type":"message",
"role":"assistant",
"status":status,
"content":[{"type":"output_text","text":text,"annotations":[]}]
}],
"usage":{
"input_tokens":usage.input_tokens,
"output_tokens":usage.output_tokens,
"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),
"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}
},
"error":null,
"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}
})
}
impl Trace {
pub(super) fn beginning(&mut self) -> Vec<Bytes> {
let mut initial = response_value(&self.id, &self.model, "", "in_progress", &self.usage);
initial["output"] = json!([]);
initial["usage"] = Value::Null;
let item = json!({"id":format!("msg_{}",self.id),"type":"message","role":"assistant","status":"in_progress","content":[]});
vec![self.event("response.created",json!({"response":initial})),self.event("response.in_progress",json!({"response":initial})),self.event("response.output_item.added",json!({"output_index":0,"item":item})),self.event("response.content_part.added",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}))]
let item_id = format!("msg_{}", self.id);
let item = json!({"id":item_id,"type":"message","role":"assistant","status":"in_progress","content":[]});
let part = json!({"type":"output_text","text":"","annotations":[]});
vec![
self.event("response.created", json!({"response":initial})),
self.event("response.in_progress", json!({"response":initial})),
self.event(
"response.output_item.added",
json!({"output_index":0,"item":item}),
),
self.event(
"response.content_part.added",
json!({"item_id":item_id,"output_index":0,"content_index":0,"part":part}),
),
]
}
pub(super) fn interrupted(&mut self) -> Bytes {
let mut failed = response_value(&self.id, &self.model, &self.text, "failed", &self.usage);
@@ -37,52 +72,70 @@ impl Trace {
) -> Result<Vec<Bytes>, &'static str> {
match frame.payload.ok_or("missing_payload")? {
proto::generation_frame::Payload::Accepted(_) => Ok(Vec::new()),
proto::generation_frame::Payload::Text(delta) => {
if self.text.len() + delta.text.len() > 8 * 1024 * 1024 {
return Err("response_limit");
}
self.text.push_str(&delta.text);
Ok(vec![self.event("response.output_text.delta",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"delta":delta.text}))])
}
proto::generation_frame::Payload::Text(delta) => self.text_delta(delta.text),
proto::generation_frame::Payload::Usage(usage) => {
self.usage = usage;
Ok(Vec::new())
}
proto::generation_frame::Payload::Tool(_) => Err("unadvertised_tool_output"),
proto::generation_frame::Payload::Terminal(terminal) => {
if terminal.state == 1 && !matches!(terminal.reason.as_str(), "stop" | "length") {
return Err("unadvertised_finish_reason");
}
if let Some(usage) = terminal.usage {
self.usage = usage;
}
let status = match terminal.state {
1 if terminal.reason == "length" => "incomplete",
1 => "completed",
_ => "failed",
};
let mut value =
response_value(&self.id, &self.model, &self.text, status, &self.usage);
if status == "failed" {
value["error"] =
json!({"code":"runtime_interrupted","message":"runtime_interrupted"});
}
let part = json!({"type":"output_text","text":self.text,"annotations":[]});
let item = value["output"][0].clone();
let mut events = Vec::new();
if status != "failed" {
events.push(self.event("response.output_text.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"text":self.text})));
events.push(self.event("response.content_part.done",json!({"item_id":format!("msg_{}",self.id),"output_index":0,"content_index":0,"part":part})));
events.push(self.event(
"response.output_item.done",
json!({"output_index":0,"item":item}),
));
}
events.push(self.event(&format!("response.{status}"), json!({"response":value})));
Ok(events)
}
proto::generation_frame::Payload::Terminal(terminal) => self.terminal(terminal),
}
}
fn text_delta(&mut self, delta: String) -> Result<Vec<Bytes>, &'static str> {
if self.text.len() + delta.len() > 8 * 1024 * 1024 {
return Err("response_limit");
}
self.text.push_str(&delta);
let item_id = format!("msg_{}", self.id);
Ok(vec![self.event(
"response.output_text.delta",
json!({"item_id":item_id,"output_index":0,"content_index":0,"delta":delta}),
)])
}
fn terminal(&mut self, terminal: proto::Terminal) -> Result<Vec<Bytes>, &'static str> {
if terminal.state == 1 && !matches!(terminal.reason.as_str(), "stop" | "length") {
return Err("unadvertised_finish_reason");
}
if let Some(usage) = terminal.usage {
self.usage = usage;
}
let status = match terminal.state {
1 if terminal.reason == "length" => "incomplete",
1 => "completed",
_ => "failed",
};
let mut value = response_value(&self.id, &self.model, &self.text, status, &self.usage);
if status == "failed" {
value["error"] = json!({"code":"runtime_interrupted","message":"runtime_interrupted"});
}
Ok(self.terminal_events(status, value))
}
fn terminal_events(&mut self, status: &str, value: Value) -> Vec<Bytes> {
let mut events = Vec::new();
if status != "failed" {
events.extend(self.completion_events(value["output"][0].clone()));
}
events.push(self.event(&format!("response.{status}"), json!({"response":value})));
events
}
fn completion_events(&mut self, item: Value) -> Vec<Bytes> {
let item_id = format!("msg_{}", self.id);
let part = json!({"type":"output_text","text":self.text,"annotations":[]});
vec![
self.event(
"response.output_text.done",
json!({"item_id":item_id,"output_index":0,"content_index":0,"text":self.text}),
),
self.event(
"response.content_part.done",
json!({"item_id":item_id,"output_index":0,"content_index":0,"part":part}),
),
self.event(
"response.output_item.done",
json!({"output_index":0,"item":item}),
),
]
}
}
pub(super) async fn accepted(
client: &mut RuntimeClient,
@@ -134,90 +187,154 @@ pub(super) async fn responses(State(r): State<Registry>, h: HeaderMap, body: Byt
if r.0.experimental_native_tools && needs_tool_adapter(&v) {
return tool_responses(r, index, v).await;
}
let (prompt, cap, sampling) = match render(&v) {
Ok(v) => v,
Err(e) => return error(StatusCode::BAD_REQUEST, e),
};
let Some((mut client, snapshot)) = r.observe(index).await else {
return error(StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable");
};
let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else {
return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready");
let (stream, trace) = match open_generation(&r, index, model, &v).await {
Ok(opened) => opened,
Err(response) => return response,
};
if v.get("stream") == Some(&Value::Bool(true)) {
text_event_stream(trace, stream)
} else {
text_json(trace, stream).await
}
}
/// Renders the request, dispatches it to the runtime member and starts the trace of its response.
async fn open_generation(
r: &Registry,
index: usize,
model: &str,
v: &Value,
) -> Result<(RuntimeGeneration, Trace), Response> {
let (prompt, cap, sampling) = render(v).map_err(|e| error(StatusCode::BAD_REQUEST, e))?;
let (mut client, epoch, loaded) = ready_member(r, index).await?;
let request_id = uuid::Uuid::new_v4().to_string();
let mut generate = proto::GenerateRequest {
request_id: request_id.clone(),
expected_epoch: snapshot.epoch,
expected_epoch: epoch,
handle: loaded.handle,
prompt,
max_output_tokens: cap,
..Default::default()
};
crate::runtime_sampling::apply(&mut generate, &sampling);
let stream = match accepted(&mut client, generate).await {
Ok(s) => s,
Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"),
};
let mut trace = Trace {
let stream = accepted(&mut client, generate)
.await
.map_err(|_| error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"))?;
let trace = Trace {
id: format!("resp_{}", request_id.replace('-', "")),
model: model.to_owned(),
text: String::new(),
usage: proto::Usage::default(),
sequence: 0,
};
if v.get("stream") == Some(&Value::Bool(true)) {
let output = async_stream::stream! {
for event in trace.beginning(){yield Ok::<Bytes,std::io::Error>(event);}
let mut stream=stream;
loop {match tokio::time::timeout(Duration::from_secs(3600),stream.message()).await {
Ok(Ok(Some(frame)))=>{let terminal=matches!(frame.payload,Some(proto::generation_frame::Payload::Terminal(_)));match trace.frame(frame){Ok(events)=>for event in events{yield Ok(event);},Err(_)=>{yield Ok(trace.interrupted());break;}}if terminal{break;}},
_=>{yield Ok(trace.interrupted());break;}
}}
};
let mut response = Body::from_stream(output).into_response();
response
.headers_mut()
.insert("content-type", "text/event-stream".parse().unwrap());
response
.headers_mut()
.insert("cache-control", "no-store".parse().unwrap());
response
} else {
let mut stream = stream;
let mut terminal = None;
Ok((stream, trace))
}
/// The member's client, its epoch and the model it has loaded; a refusal response when it is not ready.
pub(super) async fn ready_member(
r: &Registry,
index: usize,
) -> Result<(RuntimeClient, String, proto::LoadedModel), Response> {
let Some((client, snapshot)) = r.observe(index).await else {
return Err(error(
StatusCode::SERVICE_UNAVAILABLE,
"runtime_unavailable",
));
};
let Some(loaded) = snapshot.loaded.filter(|_| snapshot.model_ready) else {
return Err(error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready"));
};
Ok((client, snapshot.epoch, loaded))
}
/// Feeds one runtime frame to the trace: the events to send and whether the stream ends here.
fn relay_frame(trace: &mut Trace, frame: proto::GenerationFrame) -> (Vec<Bytes>, bool) {
let terminal = matches!(
frame.payload,
Some(proto::generation_frame::Payload::Terminal(_))
);
match trace.frame(frame) {
Ok(events) => (events, terminal),
Err(_) => (vec![trace.interrupted()], true),
}
}
fn text_event_stream(mut trace: Trace, mut stream: RuntimeGeneration) -> Response {
let output = async_stream::stream! {
for event in trace.beginning() { yield Ok::<Bytes, std::io::Error>(event); }
loop {
match tokio::time::timeout(Duration::from_secs(3600), stream.message()).await {
Ok(Ok(Some(frame))) => {
if let Some(proto::generation_frame::Payload::Terminal(t)) = &frame.payload {
terminal = Some(t.clone());
}
if trace.frame(frame).is_err() {
return error(StatusCode::BAD_GATEWAY, "runtime_protocol_failed");
}
}
Ok(Ok(None)) => break,
_ => return error(StatusCode::BAD_GATEWAY, "runtime_interrupted"),
let (events, stop) = relay_frame(&mut trace, frame);
for event in events { yield Ok(event); }
if stop { break; }
},
_ => { yield Ok(trace.interrupted()); break; }
}
}
let Some(t) = terminal else {
return error(StatusCode::BAD_GATEWAY, "runtime_missing_terminal");
};
if t.state != 1 {
return error(StatusCode::BAD_GATEWAY, "runtime_generation_failed");
};
event_stream_response(Body::from_stream(output))
}
/// A response that carries server-sent events and is never cached.
pub(super) fn event_stream_response(body: Body) -> Response {
let mut response = body.into_response();
response
.headers_mut()
.insert("content-type", "text/event-stream".parse().unwrap());
response
.headers_mut()
.insert("cache-control", "no-store".parse().unwrap());
response
}
/// Reads the stream to its end; the terminal frame, if one arrived, or the error response for a broken stream.
async fn collect_terminal(
trace: &mut Trace,
stream: &mut RuntimeGeneration,
) -> Result<Option<proto::Terminal>, Response> {
let mut terminal = None;
loop {
match tokio::time::timeout(Duration::from_secs(3600), stream.message()).await {
Ok(Ok(Some(frame))) => {
if let Some(proto::generation_frame::Payload::Terminal(t)) = &frame.payload {
terminal = Some(t.clone());
}
if trace.frame(frame).is_err() {
return Err(error(StatusCode::BAD_GATEWAY, "runtime_protocol_failed"));
}
}
Ok(Ok(None)) => break,
_ => return Err(error(StatusCode::BAD_GATEWAY, "runtime_interrupted")),
}
Json(response_value(
&trace.id,
&trace.model,
&trace.text,
if t.reason == "length" {
"incomplete"
} else {
"completed"
},
&trace.usage,
))
.into_response()
}
Ok(terminal)
}
async fn text_json(mut trace: Trace, mut stream: RuntimeGeneration) -> Response {
let terminal = match collect_terminal(&mut trace, &mut stream).await {
Ok(terminal) => terminal,
Err(response) => return response,
};
let Some(t) = terminal else {
return error(StatusCode::BAD_GATEWAY, "runtime_missing_terminal");
};
if t.state != 1 {
return error(StatusCode::BAD_GATEWAY, "runtime_generation_failed");
}
let status = if t.reason == "length" {
"incomplete"
} else {
"completed"
};
Json(response_value(
&trace.id,
&trace.model,
&trace.text,
status,
&trace.usage,
))
.into_response()
}
pub(super) fn needs_tool_adapter(value: &Value) -> bool {
+51 -47
View File
@@ -140,6 +140,43 @@ impl Drop for GenerationResponse {
}
}
}
/// A frame of the request's stream.
fn frame_of(
id: &str,
epoch: &str,
sequence: u64,
payload: proto::generation_frame::Payload,
) -> proto::GenerationFrame {
proto::GenerationFrame {
request_id: id.to_owned(),
epoch: epoch.to_owned(),
sequence,
payload: Some(payload),
}
}
/// The next backend event and whether the backend really sent it; a closed channel yields a synthesized failure.
fn next_event(source: &mut api::GenerationStream) -> (api::GenerationEvent, bool) {
match source.recv() {
Ok(Some(event)) => (event, true),
_ => (
api::GenerationEvent::Terminal(api::GenerationTerminal::Failed {
code: api::ErrorCode::Internal,
message: "missing_terminal".into(),
retryable: false,
}),
false,
),
}
}
/// The terminal that replaces an event whose frame exceeds the frame limit.
fn frame_limit_failure(id: &str, epoch: &str, sequence: u64) -> proto::GenerationFrame {
let failed = api::GenerationEvent::Terminal(api::GenerationTerminal::Failed {
code: api::ErrorCode::ResourceExhausted,
message: "output_frame_limit".into(),
retryable: false,
});
frame_of(id, epoch, sequence, event_to_proto(failed))
}
pub(super) fn pump(
inner: Arc<Inner>,
id: String,
@@ -148,63 +185,30 @@ pub(super) fn pump(
sender: mpsc::Sender<Result<proto::GenerationFrame, Status>>,
) {
let mut sequence = 1;
let accepted = proto::GenerationFrame {
request_id: id.clone(),
epoch: epoch.clone(),
sequence,
payload: Some(proto::generation_frame::Payload::Accepted(
proto::Accepted { accepted: true },
)),
};
if sender.blocking_send(Ok(accepted)).is_err() {
let accepted = proto::generation_frame::Payload::Accepted(proto::Accepted { accepted: true });
if sender
.blocking_send(Ok(frame_of(&id, &epoch, sequence, accepted)))
.is_err()
{
cancel_and_drain(&inner, &id, &mut source);
return;
}
loop {
let (event, confirmed) = match source.recv() {
Ok(Some(event)) => (event, true),
_ => (
api::GenerationEvent::Terminal(api::GenerationTerminal::Failed {
code: api::ErrorCode::Internal,
message: "missing_terminal".into(),
retryable: false,
}),
false,
),
};
let (event, confirmed) = next_event(&mut source);
sequence += 1;
let terminal = matches!(event, api::GenerationEvent::Terminal(_));
let frame = proto::GenerationFrame {
request_id: id.clone(),
epoch: epoch.clone(),
sequence,
payload: Some(event_to_proto(event)),
let frame = frame_of(&id, &epoch, sequence, event_to_proto(event));
let oversized = frame.encoded_len() > FRAME_LIMIT;
let outgoing = if oversized {
frame_limit_failure(&id, &epoch, sequence)
} else {
frame
};
if frame.encoded_len() > FRAME_LIMIT {
let failed = proto::GenerationFrame {
request_id: id.clone(),
epoch: epoch.clone(),
sequence,
payload: Some(event_to_proto(api::GenerationEvent::Terminal(
api::GenerationTerminal::Failed {
code: api::ErrorCode::ResourceExhausted,
message: "output_frame_limit".into(),
retryable: false,
},
))),
};
let _ = sender.blocking_send(Ok(failed));
let sent = sender.blocking_send(Ok(outgoing)).is_ok();
if oversized || !sent || terminal {
settle(&inner, &id, &mut source, terminal, confirmed);
return;
}
if sender.blocking_send(Ok(frame)).is_err() {
settle(&inner, &id, &mut source, terminal, confirmed);
return;
}
if terminal {
settle(&inner, &id, &mut source, terminal, confirmed);
break;
}
}
}
+137 -88
View File
@@ -2,122 +2,171 @@
use super::*;
/// The request is within the documented ranges; returns the backend sampling controls.
fn check_generation(command: &proto::GenerateRequest) -> Result<api::SamplingOptions, Status> {
if command.prompt.len() > 1024 * 1024
|| command.max_output_tokens == 0
|| command.max_output_tokens > api::MAX_OUTPUT_TOKENS
{
return Err(refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
));
}
// Sampling is served by the backend (Original sampler chain); the Original's documented
// ranges are enforced here too, so an out-of-contract request never reaches a worker.
crate::runtime_sampling::to_backend(command).map_err(|()| {
refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
)
})
}
/// No generation can start: one is in flight, a lifecycle operation runs, the server stops or the sequence ends.
fn generation_full(state: &State) -> bool {
state.active.is_some() || state.lifecycle_busy || state.stopping || state.sequence == u64::MAX
}
/// The backend request for `command`; the prompt moves out of the command.
fn backend_request(
command: &mut proto::GenerateRequest,
sampling: api::SamplingOptions,
) -> api::GenerationRequest {
api::GenerationRequest {
request_id: command.request_id.clone(),
prompt: std::mem::take(&mut command.prompt),
max_output_tokens: command.max_output_tokens,
temperature_milli: command.temperature_milli,
sampling,
}
}
impl RuntimeServer {
pub(super) async fn handle_generate(
&self,
request: Request<proto::GenerateRequest>,
) -> Result<Response<WireStream<proto::GenerationFrame>>, Status> {
let _permit = self.authorize(&request, MESSAGE_LIMIT)?;
let command = request.into_inner();
let mut command = request.into_inner();
uuid(&command.request_id)?;
if command.prompt.len() > 1024 * 1024
|| command.max_output_tokens == 0
|| command.max_output_tokens > api::MAX_OUTPUT_TOKENS
{
return Err(refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
));
}
// Sampling is served by the backend (Original sampler chain); the Original's documented
// ranges are enforced here too, so an out-of-contract request never reaches a worker.
let sampling = crate::runtime_sampling::to_backend(&command).map_err(|()| {
refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
)
})?;
let loaded = {
let mut state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
if state.requests.contains(&command.request_id) {
// An old ID may have accepted/visible effects. Its rejection
// cannot authorize a retry of that identity on another member,
// including when this member's registry or slot is full.
return Err(Status::already_exists("generation_not_replayed"));
}
if state.active.is_some()
|| state.lifecycle_busy
|| state.stopping
|| state.sequence == u64::MAX
{
return Err(refusal(
tonic::Code::ResourceExhausted,
"generation_capacity",
));
}
let loaded = state
.loaded
.as_ref()
.filter(|m| m.handle == command.handle)
.cloned()
.ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))?;
if !state.capabilities.supports(&loaded.descriptor) {
return Err(refusal(tonic::Code::FailedPrecondition, "model_not_ready"));
}
state.requests.insert(&command.request_id);
state.active = Some(command.request_id.clone());
publish(&self.inner, &mut state);
loaded
};
let inner = self.inner.clone();
let backend_request = api::GenerationRequest {
request_id: command.request_id.clone(),
prompt: command.prompt,
max_output_tokens: command.max_output_tokens,
temperature_milli: command.temperature_milli,
sampling,
};
let sampling = check_generation(&command)?;
let loaded = self.reserve_generation(&command)?;
let backend_request = backend_request(&mut command, sampling);
let mut acceptance_guard = AcceptanceGuard {
inner: self.inner.clone(),
id: command.request_id.clone(),
armed: true,
};
let stream = self
.start_backend(loaded, backend_request, &mut acceptance_guard)
.await?;
Ok(self.stream_response(
command.request_id,
command.expected_epoch,
stream,
&mut acceptance_guard,
))
}
/// Takes the generation slot for the request and returns the model it runs on.
fn reserve_generation(
&self,
command: &proto::GenerateRequest,
) -> Result<api::LoadedModel, Status> {
let mut state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
if state.requests.contains(&command.request_id) {
// An old ID may have accepted/visible effects. Its rejection
// cannot authorize a retry of that identity on another member,
// including when this member's registry or slot is full.
return Err(Status::already_exists("generation_not_replayed"));
}
if generation_full(&state) {
return Err(refusal(
tonic::Code::ResourceExhausted,
"generation_capacity",
));
}
let loaded = loaded_with_handle(&state, &command.handle)?;
if !state.capabilities.supports(&loaded.descriptor) {
return Err(refusal(tonic::Code::FailedPrecondition, "model_not_ready"));
}
state.requests.insert(&command.request_id);
state.active = Some(command.request_id.clone());
publish(&self.inner, &mut state);
Ok(loaded)
}
/// Starts the generation in the backend; a rejection settles the reservation before it is returned.
async fn start_backend(
&self,
loaded: api::LoadedModel,
backend_request: api::GenerationRequest,
guard: &mut AcceptanceGuard,
) -> Result<api::GenerationStream, Status> {
let inner = self.inner.clone();
let id = backend_request.request_id.clone();
let started = tokio::task::spawn_blocking(move || {
lock(&inner.backend)?
.start_generation(&loaded, backend_request)
.map_err(|e| backend_status(&e))
})
.await;
let stream = match started {
Ok(Ok(stream)) => stream,
match started {
Ok(Ok(stream)) => Ok(stream),
other => {
let status = match other {
Ok(Err(status)) => status,
_ => Status::internal("generation_acceptance_uncertain"),
};
if status
.metadata()
.get("x-leleka-accepted")
.and_then(|v| v.to_str().ok())
== Some("false")
{
acceptance_guard.armed = false;
// This reservation is proved to have produced no accepted
// effects. Release only it, so the daemon's bounded retry
// may reuse the same identity. Uncertain/accepted IDs stay.
let mut state = lock(&self.inner.state)?;
state.requests.remove(&command.request_id);
if state.active.as_deref() == Some(&command.request_id) {
state.active = None;
}
publish(&self.inner, &mut state);
} else {
close_admission(&self.inner);
}
return Err(status);
self.settle_rejection(&status, &id, guard)?;
Err(status)
}
};
}
}
/// A proven nonacceptance releases the reservation; anything else closes admission.
fn settle_rejection(
&self,
status: &Status,
id: &str,
guard: &mut AcceptanceGuard,
) -> Result<(), Status> {
if !proves_nonacceptance(status) {
close_admission(&self.inner);
return Ok(());
}
guard.armed = false;
// This reservation is proved to have produced no accepted
// effects. Release only it, so the daemon's bounded retry
// may reuse the same identity. Uncertain/accepted IDs stay.
let mut state = lock(&self.inner.state)?;
state.requests.remove(id);
if state.active.as_deref() == Some(id) {
state.active = None;
}
publish(&self.inner, &mut state);
Ok(())
}
/// Hands the accepted stream to the pump and wraps its receiver as the response.
fn stream_response(
&self,
id: String,
epoch: String,
stream: api::GenerationStream,
guard: &mut AcceptanceGuard,
) -> Response<WireStream<proto::GenerationFrame>> {
let (sender, receiver) = mpsc::channel(EVENT_QUEUE);
let inner = self.inner.clone();
let id = command.request_id.clone();
let epoch = command.expected_epoch.clone();
tokio::task::spawn_blocking(move || pump(inner, id, epoch, stream, sender));
acceptance_guard.armed = false;
let pumped_id = id.clone();
tokio::task::spawn_blocking(move || pump(inner, pumped_id, epoch, stream, sender));
guard.armed = false;
let guarded = GenerationResponse {
receiver: ReceiverStream::new(receiver),
inner: self.inner.clone(),
id: command.request_id,
id,
terminal: false,
};
let mut response = Response::new(Box::pin(guarded) as WireStream<proto::GenerationFrame>);
@@ -125,6 +174,6 @@ impl RuntimeServer {
"x-leleka-accepted",
"true".parse().expect("literal metadata"),
);
Ok(response)
response
}
}
+28 -15
View File
@@ -75,23 +75,36 @@ pub(super) fn snapshot(state: &State) -> proto::Snapshot {
capabilities_to_proto(&state.capabilities)
}),
active_request_id: state.active.clone().unwrap_or_default(),
prefix_cache_json: if state.stopping {
String::new()
} else {
state.prefix_cache_json.clone()
},
memory_json: if state.stopping {
String::new()
} else {
state.memory_json.clone()
},
telemetry_json: if state.stopping {
String::new()
} else {
state.telemetry_json.clone()
},
prefix_cache_json: unless_stopping(state, &state.prefix_cache_json),
memory_json: unless_stopping(state, &state.memory_json),
telemetry_json: unless_stopping(state, &state.telemetry_json),
}
}
/// A report document of the snapshot: empty once the server is stopping.
fn unless_stopping(state: &State, document: &str) -> String {
if state.stopping {
String::new()
} else {
document.to_owned()
}
}
/// The loaded model when `handle` names it; any other handle is stale.
pub(super) fn loaded_with_handle(state: &State, handle: &str) -> Result<api::LoadedModel, Status> {
state
.loaded
.as_ref()
.filter(|m| m.handle == handle)
.cloned()
.ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))
}
/// The status proves the command was not accepted by the backend (so its identity may be retried).
pub(super) fn proves_nonacceptance(status: &Status) -> bool {
status
.metadata()
.get("x-leleka-accepted")
.and_then(|v| v.to_str().ok())
== Some("false")
}
pub(super) fn publish(inner: &Inner, state: &mut State) {
// Saturation closes future mutations rather than wrapping the cursor.
state.sequence = state.sequence.saturating_add(1);
+208 -150
View File
@@ -1,6 +1,175 @@
//! The model RPCs: load, unload and reconfigure.
use super::*;
use std::ops::ControlFlow;
type LoadResult = Result<(api::LoadedModel, api::BackendCapabilities), Status>;
/// The final phase, reason and loaded model of a lifecycle operation.
type Outcome = (
proto::operation_result::State,
&'static str,
Option<proto::LoadedModel>,
);
/// The descriptor and the config a load request names; each must be present and valid.
fn load_arguments(
command: &proto::LoadRequest,
) -> Result<(api::ModelDescriptor, api::RuntimeConfig), Status> {
let model = descriptor_from_proto(
command
.model
.as_ref()
.ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_model"))?,
)?;
let config = config_from_proto(
command
.config
.as_ref()
.ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_config"))?,
)?;
Ok((model, config))
}
/// Loads the model in the backend and validates what it returned against the request.
fn backend_load(
inner: &Inner,
model: &api::ModelDescriptor,
config: &api::RuntimeConfig,
) -> LoadResult {
let mut backend = lock(&inner.backend)?;
let loaded = backend
.load(model.clone(), config.clone())
.map_err(|e| backend_status(&e))?;
loaded
.validate_for_load(model, config)
.map_err(|_| Status::internal("invalid_backend_load_result"))?;
Ok((loaded, backend.capabilities()))
}
/// Applies the load result to the state; returns the operation's final phase, reason and loaded model.
fn load_outcome(state: &mut State, result: LoadResult) -> Outcome {
match result {
Ok((loaded, capabilities)) => {
state.loaded = Some(loaded.clone());
state.capabilities = capabilities;
(
proto::operation_result::State::Completed,
"completed",
Some(loaded_to_proto(&loaded)),
)
}
Err(status) if proves_nonacceptance(&status) => {
(proto::operation_result::State::Failed, "load_failed", None)
}
Err(_) => {
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
(
proto::operation_result::State::Indeterminate,
"load_uncertain",
None,
)
}
}
}
/// Records the final result of the guarded operation, opens the lifecycle gate and publishes the change.
fn finish_operation(
inner: &Inner,
state: &mut State,
guard: &mut LifecycleGuard,
outcome: Outcome,
) {
let (phase, reason, loaded) = outcome;
if let Some(operation) = state.operations.get_mut(&guard.operation_id) {
operation.result.state = phase as i32;
operation.result.reason = reason.into();
operation.result.loaded = loaded;
}
state.lifecycle_busy = false;
guard.armed = false;
publish(inner, state);
}
/// The blocking part of a load: the backend call, then the state update under the same guard.
fn run_load(
inner: Arc<Inner>,
operation_id: String,
model: api::ModelDescriptor,
config: api::RuntimeConfig,
) {
let mut guard = LifecycleGuard {
inner: inner.clone(),
operation_id,
armed: true,
};
let result = backend_load(&inner, &model, &config);
if let Ok(mut state) = inner.state.lock() {
let outcome = load_outcome(&mut state, result);
finish_operation(&inner, &mut state, &mut guard, outcome);
}
}
/// The blocking part of an unload; a failed or uncertain unload also closes model admission.
fn run_unload(inner: Arc<Inner>, operation_id: String, loaded: api::LoadedModel) {
let mut guard = LifecycleGuard {
inner: inner.clone(),
operation_id,
armed: true,
};
let result =
lock(&inner.backend).and_then(|mut b| b.unload(loaded).map_err(|e| backend_status(&e)));
if let Ok(mut state) = inner.state.lock() {
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
let outcome = if result.is_ok() {
(proto::operation_result::State::Completed, "completed", None)
} else {
(
proto::operation_result::State::Indeterminate,
"unload_uncertain",
None,
)
};
finish_operation(&inner, &mut state, &mut guard, outcome);
}
}
/// The wire name of a backend error code.
fn reconfigure_error_code(code: &api::ErrorCode) -> &'static str {
match code {
api::ErrorCode::InvalidRequest => "invalid",
api::ErrorCode::UnsupportedModel => "unsupported",
api::ErrorCode::ResourceExhausted => "exhausted",
api::ErrorCode::BackendUnavailable => "unavailable",
api::ErrorCode::Internal => "internal",
}
}
/// The reply to a reconfigure request from the backend outcome.
fn reconfigure_reply(
command: proto::ReconfigureRequest,
outcome: Result<String, api::BackendError>,
) -> proto::ReconfigureReply {
match outcome {
Ok(effective) => proto::ReconfigureReply {
operation_id: command.operation_id,
epoch: command.expected_epoch,
ok: true,
effective_json: effective,
..Default::default()
},
Err(error) => proto::ReconfigureReply {
operation_id: command.operation_id,
epoch: command.expected_epoch,
ok: false,
error_code: reconfigure_error_code(&error.code).to_owned(),
error: error.message,
retryable: error.retryable,
..Default::default()
},
}
}
impl RuntimeServer {
pub(super) async fn handle_load(
@@ -9,18 +178,7 @@ impl RuntimeServer {
) -> Result<Response<proto::OperationResult>, Status> {
let _permit = self.authorize(&request, FRAME_LIMIT)?;
let command = request.into_inner();
let model = descriptor_from_proto(
command
.model
.as_ref()
.ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_model"))?,
)?;
let config = config_from_proto(
command
.config
.as_ref()
.ok_or_else(|| refusal(tonic::Code::InvalidArgument, "missing_config"))?,
)?;
let (model, config) = load_arguments(&command)?;
let mut canonical = command.clone();
canonical.operation_id.clear();
let digest = operation_digest(b"load\0", &canonical);
@@ -28,62 +186,8 @@ impl RuntimeServer {
self.reserve(&command.operation_id, &command.expected_epoch, digest)?;
if execute {
let inner = self.inner.clone();
tokio::task::spawn_blocking(move || {
let mut guard = LifecycleGuard {
inner: inner.clone(),
operation_id: command.operation_id.clone(),
armed: true,
};
let result = (|| {
let mut backend = lock(&inner.backend)?;
let loaded = backend
.load(model.clone(), config.clone())
.map_err(|e| backend_status(&e))?;
loaded
.validate_for_load(&model, &config)
.map_err(|_| Status::internal("invalid_backend_load_result"))?;
Ok::<_, Status>((loaded, backend.capabilities()))
})();
if let Ok(mut state) = inner.state.lock() {
let (phase, reason, loaded) = match result {
Ok((loaded, capabilities)) => {
state.loaded = Some(loaded.clone());
state.capabilities = capabilities;
(
proto::operation_result::State::Completed,
"completed",
Some(loaded_to_proto(&loaded)),
)
}
Err(status)
if status
.metadata()
.get("x-leleka-accepted")
.and_then(|v| v.to_str().ok())
== Some("false") =>
{
(proto::operation_result::State::Failed, "load_failed", None)
}
Err(_) => {
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
(
proto::operation_result::State::Indeterminate,
"load_uncertain",
None,
)
}
};
if let Some(operation) = state.operations.get_mut(&command.operation_id) {
operation.result.state = phase as i32;
operation.result.reason = reason.into();
operation.result.loaded = loaded;
}
state.lifecycle_busy = false;
guard.armed = false;
publish(&inner, &mut state);
}
});
let id = command.operation_id;
tokio::task::spawn_blocking(move || run_load(inner, id, model, config));
}
Ok(Response::new(accepted))
}
@@ -96,60 +200,36 @@ impl RuntimeServer {
let mut canonical = command.clone();
canonical.operation_id.clear();
let digest = operation_digest(b"unload\0", &canonical);
let loaded = {
let state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
// Completed duplicates are resolved even when the model was unloaded.
if let Some(old) = state.operations.get(&command.operation_id) {
if old.digest != digest {
return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict"));
}
return Ok(Response::new(old.result.clone()));
}
state
.loaded
.as_ref()
.filter(|m| m.handle == command.handle)
.cloned()
.ok_or_else(|| refusal(tonic::Code::FailedPrecondition, "stale_model_handle"))?
let loaded = match self.unload_target(&command, digest)? {
ControlFlow::Break(result) => return Ok(Response::new(result)),
ControlFlow::Continue(loaded) => loaded,
};
let (accepted, execute) =
self.reserve(&command.operation_id, &command.expected_epoch, digest)?;
if execute {
let inner = self.inner.clone();
tokio::task::spawn_blocking(move || {
let mut guard = LifecycleGuard {
inner: inner.clone(),
operation_id: command.operation_id.clone(),
armed: true,
};
let result = lock(&inner.backend)
.and_then(|mut b| b.unload(loaded).map_err(|e| backend_status(&e)));
if let Ok(mut state) = inner.state.lock() {
// Failed/uncertain unload also closes model admission.
state.loaded = None;
state.capabilities = api::BackendCapabilities::default();
if let Some(operation) = state.operations.get_mut(&command.operation_id) {
operation.result.state = if result.is_ok() {
proto::operation_result::State::Completed
} else {
proto::operation_result::State::Indeterminate
} as i32;
operation.result.reason = if result.is_ok() {
"completed"
} else {
"unload_uncertain"
}
.into();
}
state.lifecycle_busy = false;
guard.armed = false;
publish(&inner, &mut state);
}
});
let id = command.operation_id;
tokio::task::spawn_blocking(move || run_unload(inner, id, loaded));
}
Ok(Response::new(accepted))
}
/// The model an unload names, or the recorded result of a duplicate of the same operation.
fn unload_target(
&self,
command: &proto::UnloadRequest,
digest: [u8; 32],
) -> Result<ControlFlow<proto::OperationResult, api::LoadedModel>, Status> {
let state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
// Completed duplicates are resolved even when the model was unloaded.
if let Some(old) = state.operations.get(&command.operation_id) {
if old.digest != digest {
return Err(refusal(tonic::Code::AlreadyExists, "operation_conflict"));
}
return Ok(ControlFlow::Break(old.result.clone()));
}
loaded_with_handle(&state, &command.handle).map(ControlFlow::Continue)
}
pub(super) async fn handle_reconfigure(
&self,
request: Request<proto::ReconfigureRequest>,
@@ -159,16 +239,7 @@ impl RuntimeServer {
if command.settings_json.is_empty() || command.settings_json.len() > 4096 {
return Err(refusal(tonic::Code::InvalidArgument, "settings_size"));
}
{
let state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
if state.loaded.is_none() {
return Err(refusal(tonic::Code::FailedPrecondition, "no_model_loaded"));
}
if state.active.is_some() || state.lifecycle_busy {
return Err(refusal(tonic::Code::FailedPrecondition, "runtime_busy"));
}
}
self.reconfigurable(&command.expected_epoch)?;
let inner = self.inner.clone();
let settings = command.settings_json.clone();
let outcome = tokio::task::spawn_blocking(move || {
@@ -177,31 +248,18 @@ impl RuntimeServer {
})
.await
.map_err(|_| Status::internal("reconfigure_uncertain"))??;
let reply = match outcome {
Ok(effective) => proto::ReconfigureReply {
operation_id: command.operation_id,
epoch: command.expected_epoch,
ok: true,
effective_json: effective,
..Default::default()
},
Err(error) => proto::ReconfigureReply {
operation_id: command.operation_id,
epoch: command.expected_epoch,
ok: false,
error_code: match error.code {
api::ErrorCode::InvalidRequest => "invalid",
api::ErrorCode::UnsupportedModel => "unsupported",
api::ErrorCode::ResourceExhausted => "exhausted",
api::ErrorCode::BackendUnavailable => "unavailable",
api::ErrorCode::Internal => "internal",
}
.to_owned(),
error: error.message,
retryable: error.retryable,
..Default::default()
},
};
Ok(Response::new(reply))
Ok(Response::new(reconfigure_reply(command, outcome)))
}
/// A model is loaded and nothing is in flight under the current epoch.
fn reconfigurable(&self, epoch: &str) -> Result<(), Status> {
let state = lock(&self.inner.state)?;
fence(&state, epoch)?;
if state.loaded.is_none() {
return Err(refusal(tonic::Code::FailedPrecondition, "no_model_loaded"));
}
if state.active.is_some() || state.lifecycle_busy {
return Err(refusal(tonic::Code::FailedPrecondition, "runtime_busy"));
}
Ok(())
}
}
+47 -38
View File
@@ -11,6 +11,36 @@ fn cancel_ack(command: proto::CancelRequest) -> Response<proto::CancelAck> {
})
}
/// Every notification is a full bounded observation, including cursor gaps/replacement epochs.
/// It never starts or replays inference.
fn watch_stream(
watch_permit: OwnedSemaphorePermit,
mut changes: broadcast::Receiver<proto::Snapshot>,
first: proto::Snapshot,
inner: Arc<Inner>,
) -> impl Stream<Item = Result<proto::Snapshot, Status>> {
async_stream::try_stream! {
let _watch_permit = watch_permit;
let stopped = !first.transport_ready;
yield first;
if stopped { return; }
loop {
match changes.recv().await {
Ok(next) => {
let stopped = !next.transport_ready;
yield next;
if stopped { break; }
},
Err(broadcast::error::RecvError::Lagged(_)) => {
let next = current_snapshot(&inner)?;
yield next;
}
Err(broadcast::error::RecvError::Closed) => break,
}
}
}
}
impl RuntimeServer {
pub(super) async fn handle_handshake(
&self,
@@ -46,31 +76,9 @@ impl RuntimeServer {
.clone()
.try_acquire_owned()
.map_err(|_| Status::resource_exhausted("watch_capacity"))?;
let mut changes = self.inner.changes.subscribe();
let changes = self.inner.changes.subscribe();
let first = current_snapshot(&self.inner)?;
let inner = self.inner.clone();
// Every notification is a full bounded observation, including cursor
// gaps/replacement epochs. It never starts or replays inference.
let stream = async_stream::try_stream! {
let _watch_permit = watch_permit;
let stopped = !first.transport_ready;
yield first;
if stopped { return; }
loop {
match changes.recv().await {
Ok(next) => {
let stopped = !next.transport_ready;
yield next;
if stopped { break; }
},
Err(broadcast::error::RecvError::Lagged(_)) => {
let next = current_snapshot(&inner)?;
yield next;
}
Err(broadcast::error::RecvError::Closed) => break,
}
}
};
let stream = watch_stream(watch_permit, changes, first, self.inner.clone());
Ok(Response::new(Box::pin(stream)))
}
pub(super) async fn handle_operation(
@@ -108,20 +116,9 @@ impl RuntimeServer {
}
let inner = self.inner.clone();
let id = command.request_id.clone();
let outcome = tokio::task::spawn_blocking(move || {
let cancelled = lock(&inner.backend)?
.cancel(&id)
.map_err(|_| Status::internal("cancel_uncertain"));
// The request may have reached its terminal between the active
// check and the backend call; a finished request is already
// cancelled as far as the caller can observe.
if cancelled.is_err() && lock(&inner.state)?.active.as_deref() != Some(id.as_str()) {
return Ok(());
}
cancelled
})
.await
.map_err(|_| Status::internal("cancel_uncertain"))?;
let outcome = tokio::task::spawn_blocking(move || cancel_in_backend(&inner, &id))
.await
.map_err(|_| Status::internal("cancel_uncertain"))?;
outcome?;
Ok(cancel_ack(command))
}
@@ -136,3 +133,15 @@ impl RuntimeServer {
Ok(state.active.as_deref() == Some(&command.request_id))
}
}
/// Cancels `id` in the backend. The request may have reached its terminal between the active check and the backend
/// call; a finished request is already cancelled as far as the caller can observe.
fn cancel_in_backend(inner: &Inner, id: &str) -> Result<(), Status> {
let cancelled = lock(&inner.backend)?
.cancel(id)
.map_err(|_| Status::internal("cancel_uncertain"));
if cancelled.is_err() && lock(&inner.state)?.active.as_deref() != Some(id) {
return Ok(());
}
cancelled
}
@@ -5,8 +5,8 @@ use super::fixtures::{TOKEN, fixture, load_fixture, request};
use crate::runtime_client::RuntimeClient;
use std::net::SocketAddr;
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() {
/// Unavailable and internal errors do not prove nonacceptance; validation and capacity errors do.
fn assert_backend_status_proves_acceptance_only_when_certain() {
for code in [api::ErrorCode::BackendUnavailable, api::ErrorCode::Internal] {
assert!(
backend_status(&api::BackendError {
@@ -36,6 +36,78 @@ async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() {
"false"
);
}
}
/// Sixteen watches are served; the seventeenth is refused until they are dropped.
async fn assert_watch_capacity(client: &mut RuntimeClient, epoch: &str) {
let mut watches = Vec::new();
for _ in 0..16 {
let mut watch = client
.watch(proto::Cursor {
epoch: epoch.to_owned(),
sequence: 0,
})
.await
.unwrap();
assert_eq!(watch.message().await.unwrap().unwrap().epoch, epoch);
watches.push(watch);
}
assert_eq!(
client
.watch(proto::Cursor {
epoch: epoch.to_owned(),
sequence: 0
})
.await
.err()
.unwrap()
.code(),
tonic::Code::ResourceExhausted
);
drop(watches);
}
/// Fills the operation ledger up to its capacity with resolved fixture operations.
fn fill_operation_ledger(server: &RuntimeServer, epoch: &str) {
let mut state = server.inner.state.lock().unwrap();
for _ in state.operations.len()..MAX_IDS {
let id = Uuid::new_v4().to_string();
state.operations.insert(
id.clone(),
Operation {
digest: [0; 32],
result: proto::OperationResult {
operation_id: id,
epoch: epoch.to_owned(),
state: 2,
reason: "fixture".into(),
loaded: None,
},
},
);
}
}
/// A full ledger refuses a new operation but still replays a recorded one.
fn assert_full_ledger_refuses_new_operations(server: &RuntimeServer, epoch: &str) {
assert_eq!(
server
.reserve(&Uuid::new_v4().to_string(), epoch, [1; 32])
.unwrap_err()
.code(),
tonic::Code::ResourceExhausted
);
let (id, digest) = {
let state = server.inner.state.lock().unwrap();
let (id, op) = state.operations.iter().next().unwrap();
(id.clone(), op.digest)
};
assert!(!server.reserve(&id, epoch, digest).unwrap().1);
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() {
assert_backend_status_proves_acceptance_only_when_certain();
let (mut client, server, stop, task, _, _, local_address) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let mut wrong = client.clone();
@@ -47,31 +119,7 @@ async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() {
.code(),
tonic::Code::Unauthenticated
);
let mut watches = Vec::new();
for _ in 0..16 {
let mut watch = client
.watch(proto::Cursor {
epoch: epoch.clone(),
sequence: 0,
})
.await
.unwrap();
assert_eq!(watch.message().await.unwrap().unwrap().epoch, epoch);
watches.push(watch);
}
assert_eq!(
client
.watch(proto::Cursor {
epoch: epoch.clone(),
sequence: 0
})
.await
.err()
.unwrap()
.code(),
tonic::Code::ResourceExhausted
);
drop(watches);
assert_watch_capacity(&mut client, &epoch).await;
// The client rejects direct nonloopback endpoints before connecting.
let address = SocketAddr::from(([192, 0, 2, 1], 1));
assert_eq!(
@@ -107,38 +155,8 @@ async fn runtime_rpc_auth_epoch_bounds_and_operation_capacity() {
.await
.unwrap();
assert_eq!(unknown.state, 4);
{
let mut state = server.inner.state.lock().unwrap();
for _ in state.operations.len()..MAX_IDS {
let id = Uuid::new_v4().to_string();
state.operations.insert(
id.clone(),
Operation {
digest: [0; 32],
result: proto::OperationResult {
operation_id: id,
epoch: epoch.clone(),
state: 2,
reason: "fixture".into(),
loaded: None,
},
},
);
}
}
assert_eq!(
server
.reserve(&Uuid::new_v4().to_string(), &epoch, [1; 32])
.unwrap_err()
.code(),
tonic::Code::ResourceExhausted
);
let (id, digest) = {
let state = server.inner.state.lock().unwrap();
let (id, op) = state.operations.iter().next().unwrap();
(id.clone(), op.digest)
};
assert!(!server.reserve(&id, &epoch, digest).unwrap().1);
fill_operation_ledger(&server, &epoch);
assert_full_ledger_refuses_new_operations(&server, &epoch);
drop(wrong);
drop(client);
drop(server);
+49 -35
View File
@@ -40,6 +40,33 @@ pub(in super::super) fn loaded() -> api::LoadedModel {
}
}
/// What the mock backend does for a prompt: say nothing, wait for a cancel, or answer and complete.
fn run_script(prompt: &str, sink: api::GenerationSink, cancelled: &AtomicBool) {
if prompt == "missing" {
return;
}
if prompt == "slow-missing" {
// Ends without a terminal, but only after the client is gone.
std::thread::sleep(std::time::Duration::from_millis(150));
return;
}
if prompt == "wait" {
while !cancelled.load(Ordering::SeqCst) {
std::thread::park_timeout(std::time::Duration::from_millis(2));
}
let _ = sink.cancel();
return;
}
let _ = sink.emit(api::GenerationEvent::TextDelta { text: "A".into() });
let usage = api::Usage {
input_tokens: 1,
output_tokens: 1,
reused_input_tokens: 0,
};
let _ = sink.emit(api::GenerationEvent::Usage(usage.clone()));
let _ = sink.complete(api::FinishReason::Stop, usage);
}
impl api::Backend for Mock {
fn identity(&self) -> api::BackendIdentity {
api::BackendIdentity {
@@ -90,35 +117,31 @@ impl api::Backend for Mock {
let (sink, stream) = api::GenerationSink::channel();
let cancelled = self.cancel.clone();
cancelled.store(false, Ordering::SeqCst);
std::thread::spawn(move || {
if request.prompt == "missing" {
return;
}
if request.prompt == "slow-missing" {
// Ends without a terminal, but only after the client is gone.
std::thread::sleep(std::time::Duration::from_millis(150));
return;
}
if request.prompt == "wait" {
while !cancelled.load(Ordering::SeqCst) {
std::thread::park_timeout(std::time::Duration::from_millis(2));
}
let _ = sink.cancel();
return;
}
let _ = sink.emit(api::GenerationEvent::TextDelta { text: "A".into() });
let usage = api::Usage {
input_tokens: 1,
output_tokens: 1,
reused_input_tokens: 0,
};
let _ = sink.emit(api::GenerationEvent::Usage(usage.clone()));
let _ = sink.complete(api::FinishReason::Stop, usage);
});
std::thread::spawn(move || run_script(&request.prompt, sink, &cancelled));
Ok(stream)
}
}
/// Serves `server` on `listener` until the returned sender fires.
fn serve_in_background(
server: RuntimeServer,
listener: TcpListener,
) -> (
tokio::sync::oneshot::Sender<()>,
tokio::task::JoinHandle<()>,
) {
let (stop, stopped) = tokio::sync::oneshot::channel();
let task = tokio::spawn(async move {
server
.serve(listener, async {
let _ = stopped.await;
})
.await
.unwrap();
});
(stop, task)
}
pub(in super::super) async fn fixture() -> (
RuntimeClient,
RuntimeServer,
@@ -140,16 +163,7 @@ pub(in super::super) async fn fixture() -> (
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let (stop, stopped) = tokio::sync::oneshot::channel();
let owned = server.clone();
let task = tokio::spawn(async move {
owned
.serve(listener, async {
let _ = stopped.await;
})
.await
.unwrap();
});
let (stop, task) = serve_in_background(server.clone(), listener);
let client = RuntimeClient::connect(address, TOKEN.into()).await.unwrap();
(client, server, stop, task, loads, cancel, address)
}
+108 -84
View File
@@ -2,6 +2,7 @@
use super::super::*;
use super::fixtures::{fixture, load_fixture, loaded, request};
use crate::runtime_client::{RuntimeClient, RuntimeGeneration};
use std::sync::atomic::Ordering;
#[tokio::test(flavor = "current_thread")]
@@ -39,31 +40,57 @@ fn operation_entry(id: &str, state: proto::operation_result::State) -> Operation
}
}
/// The first operation already completed and a second one took the lifecycle gate.
fn seed_completed_and_accepted(server: &RuntimeServer, first: &str, second: &str) {
// The first worker already published its completion and disarmed
// nothing yet; a second operation then took the lifecycle gate.
let mut state = server.inner.state.lock().unwrap();
state.operations.insert(
first.to_owned(),
operation_entry(first, proto::operation_result::State::Completed),
);
state.operations.insert(
second.to_owned(),
operation_entry(second, proto::operation_result::State::Accepted),
);
state.lifecycle_busy = true;
state.loaded = Some(loaded());
}
/// Drops a guard for `operation_id`, armed or not.
fn drop_guard(server: &RuntimeServer, operation_id: &str, armed: bool) {
drop(LifecycleGuard {
inner: server.inner.clone(),
operation_id: operation_id.to_owned(),
armed,
});
}
/// The second operation ended as indeterminate; the finished first one is untouched.
fn assert_second_ended_first_kept(server: &RuntimeServer, first: &str, second: &str) {
let state = server.inner.state.lock().unwrap();
assert!(!state.lifecycle_busy && state.loaded.is_none());
assert_eq!(
state.operations[second].result.state,
proto::operation_result::State::Indeterminate as i32
);
assert_eq!(
state.operations[second].result.reason,
"lifecycle_worker_failed"
);
assert_eq!(
state.operations[first].result.state,
proto::operation_result::State::Completed as i32
);
}
#[tokio::test(flavor = "current_thread")]
async fn lifecycle_guard_ends_only_its_own_unresolved_operation() {
let (client, server, stop, task, _, _, _) = fixture().await;
let (first, second) = (Uuid::new_v4().to_string(), Uuid::new_v4().to_string());
{
// The first worker already published its completion and disarmed
// nothing yet; a second operation then took the lifecycle gate.
let mut state = server.inner.state.lock().unwrap();
state.operations.insert(
first.clone(),
operation_entry(&first, proto::operation_result::State::Completed),
);
state.operations.insert(
second.clone(),
operation_entry(&second, proto::operation_result::State::Accepted),
);
state.lifecycle_busy = true;
state.loaded = Some(loaded());
}
seed_completed_and_accepted(&server, &first, &second);
// A stale armed guard of the finished first operation must be inert.
drop(LifecycleGuard {
inner: server.inner.clone(),
operation_id: first.clone(),
armed: true,
});
drop_guard(&server, &first, true);
{
let state = server.inner.state.lock().unwrap();
assert!(state.lifecycle_busy && state.loaded.is_some());
@@ -73,48 +100,19 @@ async fn lifecycle_guard_ends_only_its_own_unresolved_operation() {
);
}
// A disarmed guard is inert even for its own unresolved operation.
drop(LifecycleGuard {
inner: server.inner.clone(),
operation_id: second.clone(),
armed: false,
});
drop_guard(&server, &second, false);
assert!(server.inner.state.lock().unwrap().lifecycle_busy);
// The failed worker's own unresolved operation ends as indeterminate.
drop(LifecycleGuard {
inner: server.inner.clone(),
operation_id: second.clone(),
armed: true,
});
{
let state = server.inner.state.lock().unwrap();
assert!(!state.lifecycle_busy && state.loaded.is_none());
assert_eq!(
state.operations[&second].result.state,
proto::operation_result::State::Indeterminate as i32
);
assert_eq!(
state.operations[&second].result.reason,
"lifecycle_worker_failed"
);
assert_eq!(
state.operations[&first].result.state,
proto::operation_result::State::Completed as i32
);
}
drop_guard(&server, &second, true);
assert_second_ended_first_kept(&server, &first, &second);
drop(client);
drop(server);
stop.send(()).unwrap();
task.await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission() {
let (mut client, server, stop, task, _, cancelled, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let command = request(&epoch, &handle, "wait");
let mut stream = client.generate(command.clone()).await.unwrap();
assert!(stream.message().await.unwrap().is_some());
drop(stream);
/// Waits until the client sees no active request, for at most about 200 ms.
async fn wait_until_idle(client: &mut RuntimeClient) {
for _ in 0..100 {
if client
.snapshot()
@@ -127,6 +125,33 @@ async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission()
}
tokio::time::sleep(std::time::Duration::from_millis(2)).await;
}
}
/// The stream ends with a failed, non-retryable terminal the backend never sent.
async fn assert_synthesized_terminal(missing: &mut RuntimeGeneration) {
let terminal = missing.message().await.unwrap().unwrap();
assert!(matches!(
terminal.payload,
Some(proto::generation_frame::Payload::Terminal(
proto::Terminal {
state: 2,
retryable: false,
..
}
))
));
assert!(missing.message().await.unwrap().is_none());
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission() {
let (mut client, server, stop, task, _, cancelled, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let command = request(&epoch, &handle, "wait");
let mut stream = client.generate(command.clone()).await.unwrap();
assert!(stream.message().await.unwrap().is_some());
drop(stream);
wait_until_idle(&mut client).await;
assert!(cancelled.load(Ordering::SeqCst));
assert!(
client
@@ -145,18 +170,7 @@ async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission()
.await
.unwrap();
missing.message().await.unwrap();
let terminal = missing.message().await.unwrap().unwrap();
assert!(matches!(
terminal.payload,
Some(proto::generation_frame::Payload::Terminal(
proto::Terminal {
state: 2,
retryable: false,
..
}
))
));
assert!(missing.message().await.unwrap().is_none());
assert_synthesized_terminal(&mut missing).await;
let closed = client.snapshot().await.unwrap();
assert!(!closed.model_ready);
assert!(!closed.active_request_id.is_empty());
@@ -167,22 +181,39 @@ async fn runtime_rpc_disconnect_cancels_and_missing_terminal_closes_admission()
task.await.unwrap();
}
/// Fills the request ledger so that `accepted_id` is the newest of a full ledger.
fn fill_request_ledger(server: &RuntimeServer, accepted_id: &str) {
let mut state = server.inner.state.lock().unwrap();
let capacity = state.requests.capacity();
for _ in 1..capacity {
state.requests.insert(&Uuid::new_v4().to_string());
}
state.requests.insert(accepted_id);
assert_eq!(state.requests.len(), capacity);
}
/// A new identity meets the busy slot, not a full ledger, and is proven unaccepted.
async fn assert_fresh_request_meets_busy_slot(
client: &mut RuntimeClient,
epoch: &str,
handle: &str,
) {
let fresh = client
.generate(request(epoch, handle, "A"))
.await
.err()
.unwrap();
assert_eq!(fresh.code(), tonic::Code::ResourceExhausted);
assert_eq!(fresh.metadata().get("x-leleka-accepted").unwrap(), "false");
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_accepted_identity_stays_fenced_while_a_full_ledger_rolls_over() {
let (mut client, server, stop, task, _, _, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let accepted = request(&epoch, &handle, "A");
let other_active = Uuid::new_v4().to_string();
{
let mut state = server.inner.state.lock().unwrap();
let capacity = state.requests.capacity();
// The accepted identity is the newest of a full ledger.
for _ in 1..capacity {
state.requests.insert(&Uuid::new_v4().to_string());
}
state.requests.insert(&accepted.request_id);
assert_eq!(state.requests.len(), capacity);
}
fill_request_ledger(&server, &accepted.request_id);
// A busy slot or a repeated identity is refused, whatever the ledger holds.
for active in [None, Some(accepted.request_id.clone()), Some(other_active)] {
server.inner.state.lock().unwrap().active = active.clone();
@@ -191,14 +222,7 @@ async fn runtime_rpc_accepted_identity_stays_fenced_while_a_full_ledger_rolls_ov
assert_eq!(duplicate.message(), "generation_not_replayed");
assert!(duplicate.metadata().get("x-leleka-accepted").is_none());
if active.is_some() {
// A new identity meets the busy slot, not a full ledger, and is proven unaccepted.
let fresh = client
.generate(request(&epoch, &handle, "A"))
.await
.err()
.unwrap();
assert_eq!(fresh.code(), tonic::Code::ResourceExhausted);
assert_eq!(fresh.metadata().get("x-leleka-accepted").unwrap(), "false");
assert_fresh_request_meets_busy_slot(&mut client, &epoch, &handle).await;
}
let state = server.inner.state.lock().unwrap();
assert_eq!(state.active, active);
@@ -2,45 +2,33 @@
use super::super::*;
use super::fixtures::{config, fixture, load_fixture, model, request};
use crate::runtime_client::{RuntimeClient, RuntimeGeneration};
use std::sync::atomic::Ordering;
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_load_dedup_preserves_mode_and_generation_order() {
let (mut client, server, stop, task, loads, _, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let command = {
let state = server.inner.state.lock().unwrap();
state
.operations
.values()
.next()
.unwrap()
.result
.operation_id
.clone()
};
let load = proto::LoadRequest {
operation_id: command.clone(),
expected_epoch: epoch.clone(),
model: Some(descriptor_to_proto(&model())),
config: Some(config_to_proto(&config())),
};
assert_eq!(client.load(load.clone()).await.unwrap().state, 2);
assert_eq!(loads.load(Ordering::SeqCst), 1);
let mut conflict = load;
conflict.config.as_mut().unwrap().gpu_memory_limit_bytes = Some(2048);
assert_eq!(
client.load(conflict).await.unwrap_err().code(),
tonic::Code::AlreadyExists
);
let mut stream = client
.generate(request(&epoch, &handle, "normal"))
.await
.unwrap();
/// The id of the one operation the fixture load recorded.
fn recorded_operation_id(server: &RuntimeServer) -> String {
let state = server.inner.state.lock().unwrap();
state
.operations
.values()
.next()
.unwrap()
.result
.operation_id
.clone()
}
/// The frames of a generation, read until the stream ends.
async fn read_frames(stream: &mut RuntimeGeneration) -> Vec<proto::GenerationFrame> {
let mut frames = Vec::new();
while let Some(frame) = stream.message().await.unwrap() {
frames.push(frame);
}
frames
}
/// A complete generation is accepted, one text delta, usage, then one completed terminal.
fn assert_complete_generation(frames: &[proto::GenerationFrame]) {
assert_eq!(
frames.iter().map(|f| f.sequence).collect::<Vec<_>>(),
vec![1, 2, 3, 4]
@@ -63,6 +51,10 @@ async fn runtime_rpc_load_dedup_preserves_mode_and_generation_order() {
proto::Terminal { state: 1, .. }
))
));
}
/// Loads an unqualified experimental mode and waits for the operation to fail.
async fn load_unqualified_mode(client: &mut RuntimeClient, epoch: &str) {
let mut ple = config();
ple.allow_experimental = true;
ple.inference_mode = api::InferenceMode::ExperimentalKarPle {
@@ -72,27 +64,49 @@ async fn runtime_rpc_load_dedup_preserves_mode_and_generation_order() {
client
.load(proto::LoadRequest {
operation_id: operation.clone(),
expected_epoch: epoch.clone(),
expected_epoch: epoch.to_owned(),
model: Some(descriptor_to_proto(&model())),
config: Some(config_to_proto(&ple)),
})
.await
.unwrap();
for _ in 0..100 {
if client
.operation(proto::OperationQuery {
operation_id: operation.clone(),
expected_epoch: epoch.clone(),
})
.await
.unwrap()
.state
== 3
{
let query = proto::OperationQuery {
operation_id: operation.clone(),
expected_epoch: epoch.to_owned(),
};
if client.operation(query).await.unwrap().state == 3 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(2)).await;
}
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_rpc_load_dedup_preserves_mode_and_generation_order() {
let (mut client, server, stop, task, loads, _, _) = fixture().await;
let (epoch, handle) = load_fixture(&mut client).await;
let command = recorded_operation_id(&server);
let load = proto::LoadRequest {
operation_id: command.clone(),
expected_epoch: epoch.clone(),
model: Some(descriptor_to_proto(&model())),
config: Some(config_to_proto(&config())),
};
assert_eq!(client.load(load.clone()).await.unwrap().state, 2);
assert_eq!(loads.load(Ordering::SeqCst), 1);
let mut conflict = load;
conflict.config.as_mut().unwrap().gpu_memory_limit_bytes = Some(2048);
assert_eq!(
client.load(conflict).await.unwrap_err().code(),
tonic::Code::AlreadyExists
);
let mut stream = client
.generate(request(&epoch, &handle, "normal"))
.await
.unwrap();
assert_complete_generation(&read_frames(&mut stream).await);
load_unqualified_mode(&mut client, &epoch).await;
let current = client.snapshot().await.unwrap();
assert!(current.model_ready);
assert_eq!(current.loaded.unwrap().handle, handle);
+16 -16
View File
@@ -55,6 +55,22 @@ pub(super) fn add_identity(
Some("custom") => true,
_ => return Err("unsupported_tool_type"),
};
check_tool_fields(tool, custom)?;
let name = tool["name"].as_str().ok_or("tool_name_required")?;
let flat_name = alias(name, namespace)?;
let identity = Identity {
name: name.to_owned(),
namespace: namespace.map(str::to_owned),
custom,
};
if identities.len() >= TOOL_LIMIT || identities.insert(flat_name, identity).is_some() {
return Err("tool_limit_or_duplicate_identity");
}
Ok(())
}
/// The declared fields of a function or custom tool: allowed keys, text description, object schema.
fn check_tool_fields(tool: &Value, custom: bool) -> Result<(), &'static str> {
fields(
tool,
if custom {
@@ -73,21 +89,5 @@ pub(super) fn add_identity(
}
local_refs(schema)?;
}
let name = tool["name"].as_str().ok_or("tool_name_required")?;
let flat_name = alias(name, namespace)?;
if identities.len() >= TOOL_LIMIT
|| identities
.insert(
flat_name,
Identity {
name: name.to_owned(),
namespace: namespace.map(str::to_owned),
custom,
},
)
.is_some()
{
return Err("tool_limit_or_duplicate_identity");
}
Ok(())
}
+175 -126
View File
@@ -3,6 +3,34 @@
#[allow(unused_imports)]
use super::*;
const CUSTOM_CALL_FIELDS: [&str; 7] = [
"type",
"id",
"status",
"call_id",
"name",
"namespace",
"input",
];
const FUNCTION_CALL_FIELDS: [&str; 7] = [
"type",
"id",
"status",
"call_id",
"name",
"namespace",
"arguments",
];
/// The replay of an input item list: the messages it owns and the tool calls still waiting for results.
struct Replay<'a> {
policy: &'a ToolPolicy,
owned: &'a mut Vec<(Role, String)>,
pending: Vec<Pending>,
seen: HashSet<String>,
item_ids: HashSet<String>,
}
pub(super) fn history(
input: &Value,
policy: &ToolPolicy,
@@ -16,12 +44,26 @@ pub(super) fn history(
if items.is_empty() || items.len() > ITEM_LIMIT {
return Err("input_item_limit");
}
let mut pending: Vec<Pending> = Vec::new();
let mut seen = HashSet::new();
let mut item_ids = HashSet::new();
let mut replay = Replay {
policy,
owned,
pending: Vec::new(),
seen: HashSet::new(),
item_ids: HashSet::new(),
};
for item in items {
replay.item(item)?;
}
if !replay.pending.is_empty() {
return Err("unresolved_tool_history");
}
Ok(())
}
impl Replay<'_> {
fn item(&mut self, item: &Value) -> Result<(), &'static str> {
if let Some(id) = item.get("id")
&& !item_ids.insert(valid_id(id)?.to_owned())
&& !self.item_ids.insert(valid_id(id)?.to_owned())
{
return Err("duplicate_item_id");
}
@@ -31,133 +73,140 @@ pub(super) fn history(
.transpose()?
.unwrap_or("message");
match kind {
"message" => {
fields(item, &["type", "id", "status", "role", "content"])?;
completed_item(item)?;
if !pending.is_empty() {
return Err("unresolved_tool_history");
}
let role = match item["role"].as_str() {
Some("system") => Role::System,
Some("developer") => Role::Developer,
Some("user") => Role::User,
Some("assistant") => Role::Assistant,
_ => return Err("invalid_role"),
};
owned.push((
role,
content(item.get("content").ok_or("content_required")?, false)?,
));
}
"function_call" | "custom_tool_call" => {
let custom = kind == "custom_tool_call";
fields(
item,
if custom {
&[
"type",
"id",
"status",
"call_id",
"name",
"namespace",
"input",
]
} else {
&[
"type",
"id",
"status",
"call_id",
"name",
"namespace",
"arguments",
]
},
)?;
completed_item(item)?;
if pending.iter().any(|call| call.output.is_some()) {
return Err("call_after_tool_result");
}
let id = valid_id(&item["call_id"])?;
if !seen.insert(id.to_owned()) {
return Err("duplicate_call_id");
}
let name = policy.identity(item, custom)?;
let arguments = if custom {
json!({"input":item["input"].as_str().ok_or("custom_input_required")?})
} else {
serde_json::from_str(item["arguments"].as_str().ok_or("arguments_required")?)
.map_err(|_| "invalid_history_arguments")?
};
policy.validated_call(&name, &arguments)?;
let mut markup = format!("<tool_call>\n<function={name}>\n");
for (parameter, value) in arguments.as_object().ok_or("arguments_must_be_object")? {
alias(parameter, None).map_err(|_| "unsafe_parameter_name")?;
markup.push_str(&format!("<parameter={parameter}>\n"));
if let Some(text) = value.as_str() {
markup.push_str(text);
} else {
markup.push_str(&value.to_string());
}
markup.push_str("\n</parameter>\n");
}
markup.push_str("</function>\n</tool_call>");
pending.push(Pending {
id: id.to_owned(),
custom,
markup,
output: None,
});
}
"message" => self.message(item),
"function_call" | "custom_tool_call" => self.call(item, kind == "custom_tool_call"),
"function_call_output" | "custom_tool_call_output" => {
fields(item, &["type", "id", "status", "call_id", "output"])?;
completed_item(item)?;
let id = valid_id(&item["call_id"])?;
let call = pending
.iter_mut()
.find(|call| call.id == id)
.ok_or("orphan_tool_result")?;
if call.custom != (kind == "custom_tool_call_output") || call.output.is_some() {
return Err("tool_result_identity_or_duplicate");
}
call.output = Some(content(item.get("output").ok_or("output_required")?, true)?);
if pending.iter().all(|call| call.output.is_some()) {
let call_text = pending
.iter()
.map(|call| call.markup.as_str())
.collect::<Vec<_>>()
.join("\n");
let output_text = pending
.iter()
.map(|call| {
format!(
"<tool_response>\n{}\n</tool_response>",
call.output.as_deref().unwrap_or_default()
)
})
.collect::<Vec<_>>()
.join("\n");
if let Some((Role::Assistant, text)) = owned.last_mut() {
text.truncate(text.trim_end().len());
if !text.is_empty() {
text.push_str("\n\n");
}
text.push_str(&call_text);
} else {
owned.push((Role::Assistant, call_text));
}
owned.push((Role::User, output_text));
pending.clear();
}
self.output(item, kind == "custom_tool_call_output")
}
_ => return Err("unsupported_input_item"),
_ => Err("unsupported_input_item"),
}
}
if !pending.is_empty() {
return Err("unresolved_tool_history");
fn message(&mut self, item: &Value) -> Result<(), &'static str> {
fields(item, &["type", "id", "status", "role", "content"])?;
completed_item(item)?;
if !self.pending.is_empty() {
return Err("unresolved_tool_history");
}
let role = match item["role"].as_str() {
Some("system") => Role::System,
Some("developer") => Role::Developer,
Some("user") => Role::User,
Some("assistant") => Role::Assistant,
_ => return Err("invalid_role"),
};
let text = content(item.get("content").ok_or("content_required")?, false)?;
self.owned.push((role, text));
Ok(())
}
Ok(())
fn call(&mut self, item: &Value, custom: bool) -> Result<(), &'static str> {
fields(item, call_fields(custom))?;
completed_item(item)?;
if self.pending.iter().any(|call| call.output.is_some()) {
return Err("call_after_tool_result");
}
let id = valid_id(&item["call_id"])?;
if !self.seen.insert(id.to_owned()) {
return Err("duplicate_call_id");
}
let name = self.policy.identity(item, custom)?;
let arguments = call_arguments(item, custom)?;
self.policy.validated_call(&name, &arguments)?;
let markup = call_markup(&name, &arguments)?;
self.pending.push(Pending {
id: id.to_owned(),
custom,
markup,
output: None,
});
Ok(())
}
fn output(&mut self, item: &Value, custom: bool) -> Result<(), &'static str> {
fields(item, &["type", "id", "status", "call_id", "output"])?;
completed_item(item)?;
let id = valid_id(&item["call_id"])?;
let call = self
.pending
.iter_mut()
.find(|call| call.id == id)
.ok_or("orphan_tool_result")?;
if call.custom != custom || call.output.is_some() {
return Err("tool_result_identity_or_duplicate");
}
call.output = Some(content(item.get("output").ok_or("output_required")?, true)?);
if self.pending.iter().all(|call| call.output.is_some()) {
self.flush_exchange();
}
Ok(())
}
/// Every pending call has its result: the calls join the assistant text, the results become a user turn.
fn flush_exchange(&mut self) {
let call_text = self
.pending
.iter()
.map(|call| call.markup.as_str())
.collect::<Vec<_>>()
.join("\n");
let output_text = self
.pending
.iter()
.map(|call| {
format!(
"<tool_response>\n{}\n</tool_response>",
call.output.as_deref().unwrap_or_default()
)
})
.collect::<Vec<_>>()
.join("\n");
if let Some((Role::Assistant, text)) = self.owned.last_mut() {
text.truncate(text.trim_end().len());
if !text.is_empty() {
text.push_str("\n\n");
}
text.push_str(&call_text);
} else {
self.owned.push((Role::Assistant, call_text));
}
self.owned.push((Role::User, output_text));
self.pending.clear();
}
}
fn call_fields(custom: bool) -> &'static [&'static str] {
if custom {
&CUSTOM_CALL_FIELDS
} else {
&FUNCTION_CALL_FIELDS
}
}
fn call_arguments(item: &Value, custom: bool) -> Result<Value, &'static str> {
if custom {
Ok(json!({"input":item["input"].as_str().ok_or("custom_input_required")?}))
} else {
serde_json::from_str(item["arguments"].as_str().ok_or("arguments_required")?)
.map_err(|_| "invalid_history_arguments")
}
}
/// The tool-call markup of one history call: one parameter block per argument.
fn call_markup(name: &str, arguments: &Value) -> Result<String, &'static str> {
let mut markup = format!("<tool_call>\n<function={name}>\n");
for (parameter, value) in arguments.as_object().ok_or("arguments_must_be_object")? {
alias(parameter, None).map_err(|_| "unsafe_parameter_name")?;
markup.push_str(&format!("<parameter={parameter}>\n"));
if let Some(text) = value.as_str() {
markup.push_str(text);
} else {
markup.push_str(&value.to_string());
}
markup.push_str("\n</parameter>\n");
}
markup.push_str("</function>\n</tool_call>");
Ok(markup)
}
pub(super) fn completed_item(item: &Value) -> Result<(), &'static str> {
+101 -57
View File
@@ -17,32 +17,51 @@ impl Write for Count {
}
}
const REQUEST_FIELDS: [&str; 19] = [
"model",
"input",
"instructions",
"stream",
"max_output_tokens",
"temperature",
"top_p",
"top_k",
"min_p",
"repetition_penalty",
"frequency_penalty",
"presence_penalty",
"penalty_last_n",
"seed",
"store",
"tools",
"tool_choice",
"parallel_tool_calls",
"text",
];
type Object = serde_json::Map<String, Value>;
pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
let object = request_object(request)?;
let sampling = crate::runtime_sampling::from_json(object)?;
check_text_format(object)?;
let cap = output_limit(object)?;
let (tools, parallel) = request_tools(object)?;
let policy = ToolPolicy::new(tools, object.get("tool_choice"), parallel)?;
let owned = conversation(object, &policy, !tools.is_empty(), parallel)?;
let prompt = render_prompt(&policy, &owned)?;
Ok(ToolPlan {
prompt,
max_output_tokens: cap as u32,
policy,
sampling,
})
}
/// The request object: bounded in size, only known fields, a model, no streaming type or store surprises.
fn request_object(request: &Value) -> Result<&Object, &'static str> {
serde_json::to_writer(Count(0), request).map_err(|_| "request_limit")?;
let object = fields(
request,
&[
"model",
"input",
"instructions",
"stream",
"max_output_tokens",
"temperature",
"top_p",
"top_k",
"min_p",
"repetition_penalty",
"frequency_penalty",
"presence_penalty",
"penalty_last_n",
"seed",
"store",
"tools",
"tool_choice",
"parallel_tool_calls",
"text",
],
)?;
let object = fields(request, &REQUEST_FIELDS)?;
if request["model"].as_str().is_none_or(str::is_empty) {
return Err("model_required");
}
@@ -55,13 +74,20 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
{
return Err("unsupported_sampling_or_store");
}
let sampling = crate::runtime_sampling::from_json(object)?;
Ok(object)
}
fn check_text_format(object: &Object) -> Result<(), &'static str> {
if object
.get("text")
.is_some_and(|v| v != &json!({"format":{"type":"text"}}))
{
return Err("unsupported_text_format");
}
Ok(())
}
fn output_limit(object: &Object) -> Result<u64, &'static str> {
let cap = object
.get("max_output_tokens")
.map(|v| v.as_u64().ok_or("invalid_output_limit"))
@@ -70,6 +96,10 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
if !(1..=4096).contains(&cap) {
return Err("invalid_output_limit");
}
Ok(cap)
}
fn request_tools(object: &Object) -> Result<(&[Value], bool), &'static str> {
let tools = object
.get("tools")
.map(|v| v.as_array().ok_or("invalid_tools"))
@@ -81,21 +111,24 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
.map(|v| v.as_bool().ok_or("invalid_parallel_tool_calls"))
.transpose()?
.unwrap_or(true);
let policy = ToolPolicy::new(tools, object.get("tool_choice"), parallel)?;
Ok((tools, parallel))
}
/// The system messages of the request followed by the replayed input history.
fn conversation(
object: &Object,
policy: &ToolPolicy,
has_tools: bool,
parallel: bool,
) -> Result<Vec<(Role, String)>, &'static str> {
let mut owned = Vec::new();
if let Some(instructions) = object.get("instructions") {
owned.push((
Role::System,
instructions
.as_str()
.ok_or("invalid_instructions")?
.to_owned(),
));
owned.push((Role::System, instructions_text(instructions)?));
}
if let Some(instruction) = policy.choice_instruction() {
owned.push((Role::System, instruction));
}
if !parallel && !tools.is_empty() {
if !parallel && has_tools {
owned.push((
Role::System,
"Call at most one tool in this response.".to_owned(),
@@ -103,9 +136,20 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
}
history(
object.get("input").ok_or("input_required")?,
&policy,
policy,
&mut owned,
)?;
Ok(owned)
}
fn instructions_text(instructions: &Value) -> Result<String, &'static str> {
Ok(instructions
.as_str()
.ok_or("invalid_instructions")?
.to_owned())
}
fn render_prompt(policy: &ToolPolicy, owned: &[(Role, String)]) -> Result<String, &'static str> {
let messages = owned
.iter()
.map(|(role, content)| Message {
@@ -125,12 +169,26 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
if prompt.len() > REQUEST_LIMIT {
return Err("prompt_limit");
}
Ok(ToolPlan {
prompt,
max_output_tokens: cap as u32,
policy,
sampling,
})
Ok(prompt)
}
/// A tool-history part must be a text part of the right direction and carry no output metadata.
fn part_text(part: &Value, output: bool) -> Result<&str, &'static str> {
fields(part, &["type", "text", "annotations", "logprobs"])?;
for key in ["annotations", "logprobs"] {
if part.get(key).is_some_and(|metadata| {
part["type"] != "output_text"
|| metadata.as_array().is_none_or(|items| !items.is_empty())
}) {
return Err("unsupported_output_metadata");
}
}
if !matches!(part["type"].as_str(), Some("input_text" | "output_text"))
|| (output && part["type"] != "input_text")
{
return Err("unsupported_content");
}
part["text"].as_str().ok_or("invalid_text")
}
pub(super) fn content(value: &Value, output: bool) -> Result<String, &'static str> {
@@ -143,28 +201,14 @@ pub(super) fn content(value: &Value, output: bool) -> Result<String, &'static st
}
let mut text = String::new();
for (index, part) in parts.iter().enumerate() {
fields(part, &["type", "text", "annotations", "logprobs"])?;
for key in ["annotations", "logprobs"] {
if part.get(key).is_some_and(|metadata| {
part["type"] != "output_text"
|| metadata.as_array().is_none_or(|items| !items.is_empty())
}) {
return Err("unsupported_output_metadata");
}
}
if !matches!(part["type"].as_str(), Some("input_text" | "output_text"))
|| (output && part["type"] != "input_text")
{
return Err("unsupported_content");
}
let piece = part_text(part, output)?;
if output && index > 0 {
text.push('\n');
}
text.push_str(part["text"].as_str().ok_or("invalid_text")?);
text.push_str(piece);
}
Ok(text)
}
pub(super) fn valid_id(value: &Value) -> Result<&str, &'static str> {
let id = value.as_str().ok_or("call_id_required")?;
if id.is_empty() || id.len() > 256 || !id.bytes().all(|b| b.is_ascii_graphic()) {
+126 -89
View File
@@ -12,44 +12,9 @@ impl ToolPolicy {
if tools.len() > TOOL_LIMIT {
return Err("tool_limit");
}
let mut identities = HashMap::new();
for tool in tools {
if tool["type"] == "namespace" {
fields(tool, &["type", "name", "description", "tools"])?;
optional_text(tool, "description")?;
let name = tool["name"].as_str().ok_or("namespace_name_required")?;
alias(name, None)?;
let children = tool["tools"].as_array().ok_or("namespace_tools_required")?;
if children.is_empty() || children.len() > TOOL_LIMIT {
return Err("invalid_namespace_tools");
}
for child in children {
add_identity(child, Some(name), &mut identities)?;
}
} else {
add_identity(tool, None, &mut identities)?;
}
}
let identities = declared_identities(tools)?;
let catalog = Catalog::new(tools)?;
let mut schemas = HashMap::new();
for tool in &catalog.flat {
let schema = tool
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object"}));
local_refs(&schema)?;
let validator = jsonschema::options()
.offline()
.build(&schema)
.map_err(|_| "invalid_tool_schema")?;
schemas.insert(
tool["name"]
.as_str()
.ok_or("tool_name_required")?
.to_owned(),
validator,
);
}
let schemas = tool_schemas(&catalog)?;
let mut policy = Self {
catalog,
identities,
@@ -57,39 +22,44 @@ impl ToolPolicy {
choice: Choice::Auto,
parallel,
};
policy.choice = match selection {
None => Choice::Auto,
Some(Value::String(choice)) => match choice.as_str() {
"none" => Choice::None,
"auto" => Choice::Auto,
"required" if !policy.identities.is_empty() => Choice::Required,
_ => return Err("invalid_tool_choice"),
},
Some(choice) if choice["type"] == "allowed_tools" => {
fields(choice, &["type", "mode", "tools"])?;
let required = match choice["mode"].as_str() {
Some("auto") => false,
Some("required") => true,
_ => return Err("invalid_allowed_tools_mode"),
};
let selectors = choice["tools"].as_array().ok_or("allowed_tools_required")?;
if selectors.is_empty() || selectors.len() > TOOL_LIMIT {
return Err("invalid_allowed_tools");
}
let mut names = HashSet::new();
for selector in selectors {
let name = policy.selector(selector)?;
if !names.insert(name) {
return Err("duplicate_allowed_tool");
}
}
Choice::Allowed { required, names }
}
Some(choice) => Choice::Forced(policy.selector(choice)?),
};
policy.choice = policy.choose(selection)?;
Ok(policy)
}
fn choose(&self, selection: Option<&Value>) -> Result<Choice, &'static str> {
match selection {
None => Ok(Choice::Auto),
Some(Value::String(choice)) => match choice.as_str() {
"none" => Ok(Choice::None),
"auto" => Ok(Choice::Auto),
"required" if !self.identities.is_empty() => Ok(Choice::Required),
_ => Err("invalid_tool_choice"),
},
Some(choice) if choice["type"] == "allowed_tools" => self.allowed_tools(choice),
Some(choice) => Ok(Choice::Forced(self.selector(choice)?)),
}
}
fn allowed_tools(&self, choice: &Value) -> Result<Choice, &'static str> {
fields(choice, &["type", "mode", "tools"])?;
let required = match choice["mode"].as_str() {
Some("auto") => false,
Some("required") => true,
_ => return Err("invalid_allowed_tools_mode"),
};
let selectors = choice["tools"].as_array().ok_or("allowed_tools_required")?;
if selectors.is_empty() || selectors.len() > TOOL_LIMIT {
return Err("invalid_allowed_tools");
}
let mut names = HashSet::new();
for selector in selectors {
let name = self.selector(selector)?;
if !names.insert(name) {
return Err("duplicate_allowed_tool");
}
}
Ok(Choice::Allowed { required, names })
}
pub(super) fn selector(&self, value: &Value) -> Result<String, &'static str> {
fields(value, &["type", "name", "namespace"])?;
let custom = match value["type"].as_str() {
@@ -131,7 +101,12 @@ impl ToolPolicy {
{
return Err("invalid_tool_arguments");
}
let mut item = json!({"type":"function_call","name":name,"arguments":arguments.to_string(),"status":"completed"});
let mut item = json!({
"type":"function_call",
"name":name,
"arguments":arguments.to_string(),
"status":"completed"
});
self.catalog
.restore(&mut item)
.map_err(|_| "invalid_custom_input_or_grammar")?;
@@ -151,33 +126,36 @@ impl ToolPolicy {
let mut calls = 0usize;
for segment in parsed {
match segment {
Segment::Text(text) => {
if reserved_markup(&text) {
return Err("incomplete_or_orphan_tool_markup");
}
result.push(ValidatedSegment::Text(text));
}
Segment::Text(text) => result.push(text_segment(text)?),
Segment::Call { name, arguments } => {
calls += 1;
if calls > TOOL_LIMIT || (!self.parallel && calls > 1) {
return Err("tool_call_count");
}
match &self.choice {
Choice::None => return Err("tool_choice_none"),
Choice::Forced(wanted) if wanted != &name || calls > 1 => {
return Err("forced_tool_mismatch");
}
Choice::Allowed { names, .. } if !names.contains(&name) => {
return Err("tool_not_allowed");
}
_ => {}
}
self.allow_call(&name, calls)?;
result.push(ValidatedSegment::Call(
self.validated_call(&name, &arguments)?,
));
}
}
}
self.require_calls(calls)?;
Ok(result)
}
/// The call count and the tool choice decide whether the `calls`-th call may appear.
fn allow_call(&self, name: &str, calls: usize) -> Result<(), &'static str> {
if calls > TOOL_LIMIT || (!self.parallel && calls > 1) {
return Err("tool_call_count");
}
match &self.choice {
Choice::None => Err("tool_choice_none"),
Choice::Forced(wanted) if wanted.as_str() != name || calls > 1 => {
Err("forced_tool_mismatch")
}
Choice::Allowed { names, .. } if !names.contains(name) => Err("tool_not_allowed"),
_ => Ok(()),
}
}
fn require_calls(&self, calls: usize) -> Result<(), &'static str> {
if calls == 0
&& matches!(
self.choice,
@@ -186,9 +164,8 @@ impl ToolPolicy {
{
return Err("required_tool_missing");
}
Ok(result)
Ok(())
}
pub(super) fn choice_instruction(&self) -> Option<String> {
match &self.choice {
Choice::None => None,
@@ -241,3 +218,63 @@ pub(super) fn reserved_markup(text: &str) -> bool {
|| (2..tag.len()).any(|length| text.ends_with(&tag[..length]))
})
}
fn text_segment(text: String) -> Result<ValidatedSegment, &'static str> {
if reserved_markup(&text) {
return Err("incomplete_or_orphan_tool_markup");
}
Ok(ValidatedSegment::Text(text))
}
fn declared_identities(tools: &[Value]) -> Result<HashMap<String, Identity>, &'static str> {
let mut identities = HashMap::new();
for tool in tools {
if tool["type"] == "namespace" {
add_namespace(tool, &mut identities)?;
} else {
add_identity(tool, None, &mut identities)?;
}
}
Ok(identities)
}
fn add_namespace(
tool: &Value,
identities: &mut HashMap<String, Identity>,
) -> Result<(), &'static str> {
fields(tool, &["type", "name", "description", "tools"])?;
optional_text(tool, "description")?;
let name = tool["name"].as_str().ok_or("namespace_name_required")?;
alias(name, None)?;
let children = tool["tools"].as_array().ok_or("namespace_tools_required")?;
if children.is_empty() || children.len() > TOOL_LIMIT {
return Err("invalid_namespace_tools");
}
for child in children {
add_identity(child, Some(name), identities)?;
}
Ok(())
}
fn tool_schemas(catalog: &Catalog) -> Result<HashMap<String, jsonschema::Validator>, &'static str> {
let mut schemas = HashMap::new();
for tool in &catalog.flat {
let schema = tool
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object"}));
local_refs(&schema)?;
let validator = jsonschema::options()
.offline()
.build(&schema)
.map_err(|_| "invalid_tool_schema")?;
schemas.insert(
tool["name"]
.as_str()
.ok_or("tool_name_required")?
.to_owned(),
validator,
);
}
Ok(schemas)
}
+122 -131
View File
@@ -1,9 +1,9 @@
//! Owned local listener + isolated OpenSSH stdio forwards. No remote commands.
use crate::remote::SshProfile;
use forward::forward;
use serde::{Deserialize, Serialize};
use std::{
net::SocketAddr,
process::Stdio,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
@@ -11,12 +11,12 @@ use std::{
time::Duration,
};
use tokio::{
io::AsyncWriteExt,
net::{TcpListener, TcpStream},
process::Command,
sync::{Semaphore, watch},
task::JoinSet,
};
mod forward;
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
@@ -131,26 +131,21 @@ impl Tunnel {
program: &str,
shutdown: impl Future<Output = ()> + Send,
) -> Result<(), String> {
let permits = Arc::new(Semaphore::new(self.limit));
let mut tasks = JoinSet::new();
let (cancel_tx, cancel) = watch::channel(false);
let mut gate = Gate {
permits: Arc::new(Semaphore::new(self.limit)),
cancel,
next_start: tokio::time::Instant::now(),
};
tokio::pin!(shutdown);
let mut next_start = tokio::time::Instant::now();
loop {
tokio::select! {
_=&mut shutdown=>break,
Some(_)=tasks.join_next(),if !tasks.is_empty()=>{},
accepted=self.listener.accept()=>{
let (stream,_)=accepted.map_err(|_|"tunnel accept failed")?;
let Ok(permit)=permits.clone().try_acquire_owned() else{self.counters.rejected.fetch_add(1,Ordering::Relaxed);drop(stream);continue};
self.counters.accepted.fetch_add(1,Ordering::Relaxed);self.counters.active.fetch_add(1,Ordering::Relaxed);
let args=self.args.clone();let program=program.to_string();let counters=self.counters.clone();let cancel=cancel.clone();
let start=std::cmp::max(next_start,tokio::time::Instant::now());next_start=start+Duration::from_millis(250);
tasks.spawn(async move{
let _permit=permit;let _active=Active(counters.clone());
let result=forward(stream,&program,&args,cancel,start).await;
if result.is_ok(){counters.completed.fetch_add(1,Ordering::Relaxed);}else{counters.failed.fetch_add(1,Ordering::Relaxed);}
});
_ = &mut shutdown => break,
Some(_) = tasks.join_next(), if !tasks.is_empty() => {},
accepted = self.listener.accept() => {
let (stream, _) = accepted.map_err(|_| "tunnel accept failed")?;
self.admit(&mut gate, program, stream, &mut tasks);
}
}
}
@@ -158,71 +153,58 @@ impl Tunnel {
while tasks.join_next().await.is_some() {}
Ok(())
}
}
async fn forward(
mut stream: TcpStream,
program: &str,
args: &[String],
mut cancel: watch::Receiver<bool>,
start: tokio::time::Instant,
) -> Result<(), ()> {
tokio::select! {_=tokio::time::sleep_until(start)=>{},_=cancel.changed()=>return Ok(())}
if *cancel.borrow() {
return Ok(());
/// Admits the connection within the limit (otherwise it is closed and counted as rejected) and
/// starts its forward, at most one every 250 ms.
fn admit(&self, gate: &mut Gate, program: &str, stream: TcpStream, tasks: &mut JoinSet<()>) {
let Ok(permit) = gate.permits.clone().try_acquire_owned() else {
self.counters.rejected.fetch_add(1, Ordering::Relaxed);
drop(stream);
return;
};
self.counters.accepted.fetch_add(1, Ordering::Relaxed);
self.counters.active.fetch_add(1, Ordering::Relaxed);
let start = std::cmp::max(gate.next_start, tokio::time::Instant::now());
gate.next_start = start + Duration::from_millis(250);
let connection = Connection {
program: program.to_string(),
args: self.args.clone(),
counters: self.counters.clone(),
cancel: gate.cancel.clone(),
start,
};
tasks.spawn(connection.serve(stream, permit));
}
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| ())?;
let mut input = child.stdin.take().ok_or(())?;
let mut output = child.stdout.take().ok_or(())?;
// Both directions are bounded by copy's fixed buffer and pipe/socket backpressure.
// EOF ends this SSH connection; no request replay or cross-connection byte reuse.
let result = {
let (mut read, mut write) = stream.split();
let up = async move {
let result = tokio::io::copy(&mut read, &mut input).await;
let _ = input.shutdown().await;
drop(input);
result.map(|_| ()).map_err(|_| ())
};
let down = async {
let result = tokio::io::copy(&mut output, &mut write).await;
let _ = write.shutdown().await;
result.map(|_| ()).map_err(|_| ())
};
tokio::pin!(up, down);
tokio::select! {
r=&mut down=>r,
r=&mut up=>if r.is_err(){r}else{tokio::select!{r=&mut down=>r,_=cancel.changed()=>Ok(())}},
_=cancel.changed()=>Ok(()),
}
/// What the accept loop threads between connections.
struct Gate {
permits: Arc<Semaphore>,
cancel: watch::Receiver<bool>,
next_start: tokio::time::Instant,
}
struct Connection {
program: String,
args: Vec<String>,
counters: Counters,
cancel: watch::Receiver<bool>,
start: tokio::time::Instant,
}
impl Connection {
async fn serve(self, stream: TcpStream, permit: tokio::sync::OwnedSemaphorePermit) {
let _permit = permit;
let _active = Active(self.counters.clone());
let result = forward(stream, &self.program, &self.args, self.cancel, self.start).await;
if result.is_ok() {
self.counters.completed.fetch_add(1, Ordering::Relaxed);
} else {
self.counters.failed.fetch_add(1, Ordering::Relaxed);
}
};
drop(output);
let status = match tokio::time::timeout(Duration::from_millis(100), child.wait()).await {
Ok(Ok(s)) => Some(s),
_ => {
let _ = child.start_kill();
let _ = child.wait().await;
None
}
};
let _ = stream.shutdown().await;
if status.is_some_and(|s| !s.success()) {
Err(())
} else {
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::AsyncReadExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
fn config() -> Config {
Config {
schema_version: 1,
@@ -276,73 +258,89 @@ mod tests {
assert!(Tunnel::bind(&c).await.is_err());
assert!(TcpStream::connect(c.listen).await.is_ok());
}
// A direct subprocess exercises backpressure, binary data, half-close, lifetime,
// connection admission and recreation independently of an SSH daemon.
/// A running tunnel whose connections go to `program` instead of SSH.
#[cfg(unix)]
#[tokio::test]
async fn bytes_half_close_reconnect_and_owned_shutdown() {
let t = Tunnel::bind(&config()).await.unwrap();
struct Running {
addr: SocketAddr,
stats: Counters,
stop: tokio::sync::oneshot::Sender<()>,
task: tokio::task::JoinHandle<Result<(), String>>,
}
#[cfg(unix)]
async fn start(config: &Config, program: &'static str) -> Running {
let t = Tunnel::bind(config).await.unwrap();
let addr = t.address();
let stats = t.counters();
let (stop, rx) = tokio::sync::oneshot::channel();
// cat is a byte transport fixture; remove SSH arguments only inside this test.
let t = Tunnel { args: vec![], ..t };
let task = tokio::spawn(t.run("/bin/cat", async {
let task = tokio::spawn(t.run(program, async {
let _ = rx.await;
}));
for _ in 0..2 {
let mut stream = TcpStream::connect(addr).await.unwrap();
let data: Vec<u8> = (0..300_000).map(|i| (i % 251) as u8).collect();
let (mut r, mut w) = stream.split();
let writer = async {
w.write_all(&data).await.unwrap();
w.shutdown().await.unwrap();
};
let reader = async {
let mut out = vec![];
r.read_to_end(&mut out).await.unwrap();
out
};
let (_, out) = tokio::time::timeout(Duration::from_secs(4), async {
tokio::join!(writer, reader)
})
.await
.unwrap();
assert_eq!(out, data);
Running {
addr,
stats,
stop,
task,
}
let mut a = TcpStream::connect(addr).await.unwrap();
}
/// Sends 300 kB, half-closes, and expects the same bytes back.
#[cfg(unix)]
async fn echo_round_trip(addr: SocketAddr) {
let mut stream = TcpStream::connect(addr).await.unwrap();
let data: Vec<u8> = (0..300_000).map(|i| (i % 251) as u8).collect();
let (mut r, mut w) = stream.split();
let writer = async {
w.write_all(&data).await.unwrap();
w.shutdown().await.unwrap();
};
let reader = async {
let mut out = vec![];
r.read_to_end(&mut out).await.unwrap();
out
};
let (_, out) = tokio::time::timeout(Duration::from_secs(4), async {
tokio::join!(writer, reader)
})
.await
.unwrap();
assert_eq!(out, data);
}
// A direct subprocess exercises backpressure, binary data, half-close, lifetime,
// connection admission and recreation independently of an SSH daemon.
#[cfg(unix)]
#[tokio::test]
async fn bytes_half_close_reconnect_and_owned_shutdown() {
let t = start(&config(), "/bin/cat").await;
for _ in 0..2 {
echo_round_trip(t.addr).await;
}
let mut a = TcpStream::connect(t.addr).await.unwrap();
a.write_all(b"a").await.unwrap();
let mut b = [0];
a.read_exact(&mut b).await.unwrap();
stop.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(2), task)
t.stop.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(2), t.task)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(stats.snapshot().active, 0);
assert_eq!(stats.snapshot().accepted, 3);
assert_eq!(t.stats.snapshot().active, 0);
assert_eq!(t.stats.snapshot().accepted, 3);
assert_eq!(a.read(&mut b).await.unwrap(), 0);
assert!(TcpListener::bind(addr).await.is_ok());
assert!(TcpListener::bind(t.addr).await.is_ok());
}
#[cfg(unix)]
#[tokio::test]
async fn failure_isolated_and_connection_limit_enforced() {
let mut c = config();
c.max_connections = 1;
let t = Tunnel::bind(&c).await.unwrap();
let addr = t.address();
let stats = t.counters();
let (stop, rx) = tokio::sync::oneshot::channel();
let t = Tunnel { args: vec![], ..t };
let task = tokio::spawn(t.run("/bin/cat", async {
let _ = rx.await;
}));
let mut first = TcpStream::connect(addr).await.unwrap();
let t = start(&c, "/bin/cat").await;
let mut first = TcpStream::connect(t.addr).await.unwrap();
first.write_all(b"x").await.unwrap();
let mut b = [0];
first.read_exact(&mut b).await.unwrap();
let mut second = TcpStream::connect(addr).await.unwrap();
let mut second = TcpStream::connect(t.addr).await.unwrap();
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), second.read(&mut b))
.await
@@ -350,22 +348,15 @@ mod tests {
.unwrap(),
0
);
assert_eq!(stats.snapshot().rejected, 1);
stop.send(()).unwrap();
task.await.unwrap().unwrap();
let t = Tunnel::bind(&c).await.unwrap();
let addr = t.address();
let stats = t.counters();
let (stop, rx) = tokio::sync::oneshot::channel();
let t = Tunnel { args: vec![], ..t };
let task = tokio::spawn(t.run("/usr/bin/false", async {
let _ = rx.await;
}));
let mut client = TcpStream::connect(addr).await.unwrap();
assert_eq!(t.stats.snapshot().rejected, 1);
t.stop.send(()).unwrap();
t.task.await.unwrap().unwrap();
let t = start(&c, "/usr/bin/false").await;
let mut client = TcpStream::connect(t.addr).await.unwrap();
assert_eq!(client.read(&mut b).await.unwrap(), 0);
tokio::time::sleep(Duration::from_millis(150)).await;
assert_eq!(stats.snapshot().failed, 1);
stop.send(()).unwrap();
task.await.unwrap().unwrap();
assert_eq!(t.stats.snapshot().failed, 1);
t.stop.send(()).unwrap();
t.task.await.unwrap().unwrap();
}
}
+91
View File
@@ -0,0 +1,91 @@
//! One accepted connection: an `ssh -W` child whose stdio is joined to the socket.
use std::{
process::{ExitStatus, Stdio},
time::Duration,
};
use tokio::{
io::AsyncWriteExt,
net::TcpStream,
process::{Child, ChildStdin, ChildStdout, Command},
sync::watch,
};
pub(super) async fn forward(
mut stream: TcpStream,
program: &str,
args: &[String],
mut cancel: watch::Receiver<bool>,
start: tokio::time::Instant,
) -> Result<(), ()> {
tokio::select! {_=tokio::time::sleep_until(start)=>{},_=cancel.changed()=>return Ok(())}
if *cancel.borrow() {
return Ok(());
}
let (mut child, input, output) = spawn(program, args)?;
let result = pump(&mut stream, input, output, cancel).await;
let status = reap(&mut child).await;
let _ = stream.shutdown().await;
if status.is_some_and(|s| !s.success()) {
Err(())
} else {
result
}
}
fn spawn(program: &str, args: &[String]) -> Result<(Child, ChildStdin, ChildStdout), ()> {
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| ())?;
let input = child.stdin.take().ok_or(())?;
let output = child.stdout.take().ok_or(())?;
Ok((child, input, output))
}
/// Both directions are bounded by copy's fixed buffer and pipe/socket backpressure.
/// EOF ends this SSH connection; no request replay or cross-connection byte reuse.
async fn pump(
stream: &mut TcpStream,
mut input: ChildStdin,
mut output: ChildStdout,
mut cancel: watch::Receiver<bool>,
) -> Result<(), ()> {
let (mut read, mut write) = stream.split();
let up = async move {
let result = tokio::io::copy(&mut read, &mut input).await;
let _ = input.shutdown().await;
drop(input);
result.map(|_| ()).map_err(|_| ())
};
let down = async {
let result = tokio::io::copy(&mut output, &mut write).await;
let _ = write.shutdown().await;
result.map(|_| ()).map_err(|_| ())
};
tokio::pin!(up, down);
tokio::select! {
r = &mut down => r,
r = &mut up => if r.is_err() {
r
} else {
tokio::select! { r = &mut down => r, _ = cancel.changed() => Ok(()) }
},
_ = cancel.changed() => Ok(()),
}
}
/// Gives the child a moment to exit on its own, then kills it; `None` when it had to be killed.
async fn reap(child: &mut Child) -> Option<ExitStatus> {
match tokio::time::timeout(Duration::from_millis(100), child.wait()).await {
Ok(Ok(s)) => Some(s),
_ => {
let _ = child.start_kill();
let _ = child.wait().await;
None
}
}
}
@@ -6,14 +6,8 @@ use serde_json::json;
use std::time::Duration;
use strata_control::worker::WorkerState;
#[tokio::test(flavor = "multi_thread")]
async fn a_client_disconnect_cancels_through_grpc_and_the_next_request_is_served() {
let runtime = Runtime::start(None).await;
runtime.operator_loads_the_model().await;
let stack = Stack::start("chain-cancel", runtime.address).await;
stack.wait_state(WorkerState::Ready).await;
runtime.engine.push(Script::hanging_after(&["start"]));
/// Opens a streaming response and reads until the first text delta arrived.
async fn stream_until_first_delta(stack: &Stack) -> reqwest::Response {
let mut response = stack
.client
.post(format!("{}/v1/responses", stack.base))
@@ -31,6 +25,18 @@ async fn a_client_disconnect_cancels_through_grpc_and_the_next_request_is_served
.expect("stream ended early");
seen.push_str(&String::from_utf8_lossy(&chunk));
}
response
}
#[tokio::test(flavor = "multi_thread")]
async fn a_client_disconnect_cancels_through_grpc_and_the_next_request_is_served() {
let runtime = Runtime::start(None).await;
runtime.operator_loads_the_model().await;
let stack = Stack::start("chain-cancel", runtime.address).await;
stack.wait_state(WorkerState::Ready).await;
runtime.engine.push(Script::hanging_after(&["start"]));
let response = stream_until_first_delta(&stack).await;
drop(response);
tokio::time::timeout(Duration::from_secs(10), async {
while runtime.engine.is_generating() {
+98 -59
View File
@@ -32,23 +32,8 @@ pub(super) fn tokenizer(name: &str) -> Arc<Tokenizer> {
let root = std::env::temp_dir().join(format!("api-over-runtime-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let mut vocabulary = serde_json::Map::new();
for (id, ch) in strata_control::tokenizer::byte_alphabet()
.0
.iter()
.enumerate()
{
vocabulary.insert(ch.to_string(), json!(id));
}
for (offset, token) in SPECIALS.iter().enumerate() {
vocabulary.insert((*token).into(), json!(256 + offset));
}
write_byte_vocabulary(&root);
let total = 256 + SPECIALS.len();
std::fs::write(
root.join("vocab.json"),
serde_json::to_vec(&vocabulary).unwrap(),
)
.unwrap();
std::fs::write(root.join("merges.txt"), "").unwrap();
let mut types = vec![1u8; total];
types[256..].fill(3);
@@ -70,6 +55,25 @@ pub(super) fn tokenizer(name: &str) -> Arc<Tokenizer> {
Arc::new(Tokenizer::from_assets(&root).unwrap())
}
fn write_byte_vocabulary(root: &std::path::Path) {
let mut vocabulary = serde_json::Map::new();
for (id, ch) in strata_control::tokenizer::byte_alphabet()
.0
.iter()
.enumerate()
{
vocabulary.insert(ch.to_string(), json!(id));
}
for (offset, token) in SPECIALS.iter().enumerate() {
vocabulary.insert((*token).into(), json!(256 + offset));
}
std::fs::write(
root.join("vocab.json"),
serde_json::to_vec(&vocabulary).unwrap(),
)
.unwrap();
}
pub(super) fn leleka_tokenizer_pattern() -> &'static str {
strata_control::tokenizer::QWEN35_PATTERN
}
@@ -161,60 +165,21 @@ impl Stack {
pub(super) async fn start(name: &str, address: SocketAddr) -> Self {
let tokenizer = tokenizer(name);
let prefix_view = Arc::new(strata_control::prefix_view::PrefixView::default());
let config = BackendWorkerConfig {
tokenizer: tokenizer.clone(),
model: ScriptedEngine::fixture_descriptor(),
runtime: runtime_config(),
max_context: 262_144,
max_output_tokens: 4096,
generation_timeout: None,
stall_timeout: None,
attach_retry: Duration::from_millis(50),
health_interval: Duration::from_millis(50),
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: Some(prefix_view.clone()),
memory_view: None,
};
let backend = leleka_runtime_client::backend::GrpcBackend::new(
tokio::runtime::Handle::current(),
address,
TOKEN.into(),
);
let config = worker_config(tokenizer.clone(), prefix_view.clone());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(8);
let (control, control_rx) = mpsc::channel(8);
let worker = tokio::spawn(run_backend_worker(
Box::new(backend),
Box::new(grpc_backend(address)),
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
let state = AppState {
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(),
))),
prefix_cache: prefix_view,
..Default::default()
},
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let app = router(state);
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
let state = app_state(&status, requests, control, tokenizer, prefix_view);
let (base, server) = serve_router(state).await;
Self {
base,
client: reqwest::Client::new(),
@@ -254,6 +219,80 @@ impl Stack {
}
}
fn worker_config(
tokenizer: Arc<Tokenizer>,
prefix_view: Arc<strata_control::prefix_view::PrefixView>,
) -> BackendWorkerConfig {
BackendWorkerConfig {
tokenizer,
model: ScriptedEngine::fixture_descriptor(),
runtime: runtime_config(),
max_context: 262_144,
max_output_tokens: 4096,
generation_timeout: None,
stall_timeout: None,
attach_retry: Duration::from_millis(50),
health_interval: Duration::from_millis(50),
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: Some(prefix_view),
memory_view: None,
}
}
fn app_state(
status: &Arc<RwLock<WorkerStatus>>,
requests: mpsc::Sender<strata_control::worker::GenerationCommand>,
control: mpsc::Sender<strata_control::worker::Control>,
tokenizer: Arc<Tokenizer>,
prefix_view: Arc<strata_control::prefix_view::PrefixView>,
) -> AppState {
AppState {
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,
))),
prefix_cache: prefix_view,
..Default::default()
},
..Default::default()
}
}
fn grpc_backend(address: SocketAddr) -> leleka_runtime_client::backend::GrpcBackend {
leleka_runtime_client::backend::GrpcBackend::new(
tokio::runtime::Handle::current(),
address,
TOKEN.into(),
)
}
/// The HTTP router over `state` on a free loopback port: its base URL and server task.
async fn serve_router(state: AppState) -> (String, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let app = router(state);
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
(base, server)
}
/// A loaded runtime and a stack attached to it that has reached `Ready`.
pub(super) async fn ready(name: &str) -> (Runtime, Stack) {
let runtime = Runtime::start(None).await;
runtime.operator_loads_the_model().await;
let stack = Stack::start(name, runtime.address).await;
stack.wait_state(WorkerState::Ready).await;
(runtime, stack)
}
pub(super) fn sse_events(body: &str) -> Vec<Value> {
body.split("\n\n")
.filter(|frame| !frame.trim().is_empty() && !frame.starts_with(':'))
@@ -1,6 +1,6 @@
//! 256 generations in one epoch and the prefix summary on v1 status.
use crate::harness::{Runtime, Stack, body, usage};
use crate::harness::{Runtime, Stack, body, ready, usage};
use leleka_backend_api::scripted::Script;
use serde_json::{Value, json};
use std::time::{Duration, Instant};
@@ -26,39 +26,33 @@ async fn serves_more_than_256_generations_in_one_runtime_epoch() {
runtime.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn the_engines_prefix_summary_reaches_v1_status_and_answers_prefix_match() {
let runtime = Runtime::start(None).await;
runtime.operator_loads_the_model().await;
let stack = Stack::start("chain-prefix", runtime.address).await;
stack.wait_state(WorkerState::Ready).await;
let get_status = || async {
let text = stack
.client
.get(format!("{}/v1/status", stack.base))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
serde_json::from_str::<Value>(&text).unwrap()
};
async fn get_status(stack: &Stack) -> Value {
let text = stack
.client
.get(format!("{}/v1/status", stack.base))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
serde_json::from_str::<Value>(&text).unwrap()
}
// an engine without a prefix cache reports none
assert_eq!(get_status().await["prefix_cache"], Value::Null);
// the engine's cache summary travels runtime -> snapshot (gRPC) -> worker health tick -> /v1/status
let summary = json!({
fn engine_prefix_summary() -> Value {
json!({
"version": 1, "chain_version": 1, "namespace": "00000000000000ab", "block_tokens": 2048,
"budget_bytes": 1u64 << 30, "used_bytes": 1u64 << 20, "nodes": 2, "blocks": 6, "truncated": false,
"heads": [{"h": "00000000000000a1", "tokens": 4096}, {"h": "00000000000000a2", "tokens": 12288}],
"stats": {"requests": 3, "hits": 1, "shared_hits": 1, "misses": 2, "reused_tokens": 4096, "prompt_tokens": 9000, "admitted": 2, "rejected": 0, "evicted": 0},
});
runtime.engine.set_prefix_summary(Some(summary.to_string()));
"stats": {"requests": 3, "hits": 1, "shared_hits": 1, "misses": 2, "reused_tokens": 4096,
"prompt_tokens": 9000, "admitted": 2, "rejected": 0, "evicted": 0},
})
}
async fn wait_for_prefix_cache(stack: &Stack) -> Value {
let deadline = Instant::now() + Duration::from_secs(10);
let status = loop {
let status = get_status().await;
loop {
let status = get_status(stack).await;
if status["prefix_cache"].is_object() {
break status;
}
@@ -67,14 +61,15 @@ async fn the_engines_prefix_summary_reaches_v1_status_and_answers_prefix_match()
"the summary never reached /v1/status"
);
tokio::time::sleep(Duration::from_millis(20)).await;
};
assert_eq!(status["prefix_cache"]["namespace"], "00000000000000ab");
assert_eq!(status["prefix_cache"]["heads"].as_array().unwrap().len(), 2);
}
}
async fn prefix_match_answers_the_longest_cached_prefix(stack: &Stack) {
let (code, text) = stack
.post(
"/v1/prefix_match",
&json!({"namespace": "00000000000000ab", "block_hashes": ["00000000000000a1", "00000000000000aa", "00000000000000a2"]}),
&json!({"namespace": "00000000000000ab",
"block_hashes": ["00000000000000a1", "00000000000000aa", "00000000000000a2"]}),
)
.await;
assert_eq!(code, 200, "{text}");
@@ -86,11 +81,29 @@ async fn the_engines_prefix_summary_reaches_v1_status_and_answers_prefix_match()
),
(Some(12288), Some(2048))
);
}
#[tokio::test(flavor = "multi_thread")]
async fn the_engines_prefix_summary_reaches_v1_status_and_answers_prefix_match() {
let (runtime, stack) = ready("chain-prefix").await;
// an engine without a prefix cache reports none
assert_eq!(get_status(&stack).await["prefix_cache"], Value::Null);
// the engine's cache summary travels runtime -> snapshot (gRPC) -> worker health tick -> /v1/status
runtime
.engine
.set_prefix_summary(Some(engine_prefix_summary().to_string()));
let status = wait_for_prefix_cache(&stack).await;
assert_eq!(status["prefix_cache"]["namespace"], "00000000000000ab");
assert_eq!(status["prefix_cache"]["heads"].as_array().unwrap().len(), 2);
prefix_match_answers_the_longest_cached_prefix(&stack).await;
// the cache goes away (the engine restarted without it): the view clears
runtime.engine.set_prefix_summary(None);
let deadline = Instant::now() + Duration::from_secs(10);
while !get_status().await["prefix_cache"].is_null() {
while !get_status(&stack).await["prefix_cache"].is_null() {
assert!(Instant::now() < deadline, "the summary never cleared");
tokio::time::sleep(Duration::from_millis(20)).await;
}
@@ -1,18 +1,13 @@
//! Responses over real gRPC: streaming, usage, length, tool calls and stop markers.
use crate::harness::{Runtime, Stack, assert_one_terminal, body, sse_events, text_of, usage};
use crate::harness::{
Runtime, Stack, assert_one_terminal, body, ready, sse_events, text_of, usage,
};
use leleka_backend_api::FinishReason;
use leleka_backend_api::scripted::Script;
use serde_json::{Value, json};
use strata_control::worker::WorkerState;
#[tokio::test(flavor = "multi_thread")]
async fn responses_over_real_grpc_stream_and_complete_with_the_engines_usage() {
let runtime = Runtime::start(None).await;
runtime.operator_loads_the_model().await;
let stack = Stack::start("chain-basic", runtime.address).await;
stack.wait_state(WorkerState::Ready).await;
async fn streamed_text_arrives_in_order(runtime: &Runtime, stack: &Stack) {
runtime
.engine
.push(Script::stop_with(&["hel", "lo ", "жук"], usage(11, 3)));
@@ -29,6 +24,13 @@ async fn responses_over_real_grpc_stream_and_complete_with_the_engines_usage() {
.map(|e| e["delta"].as_str().unwrap())
.collect();
assert_eq!(deltas, "hello жук");
}
#[tokio::test(flavor = "multi_thread")]
async fn responses_over_real_grpc_stream_and_complete_with_the_engines_usage() {
let (runtime, stack) = ready("chain-basic").await;
streamed_text_arrives_in_order(&runtime, &stack).await;
runtime
.engine
@@ -51,13 +53,7 @@ async fn responses_over_real_grpc_stream_and_complete_with_the_engines_usage() {
runtime.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn length_tool_call_and_stop_marker_over_real_grpc() {
let runtime = Runtime::start(None).await;
runtime.operator_loads_the_model().await;
let stack = Stack::start("chain-finish", runtime.address).await;
stack.wait_state(WorkerState::Ready).await;
async fn length_finish_is_incomplete(runtime: &Runtime, stack: &Stack) {
runtime.engine.push(Script::finishing(
&["cut"],
FinishReason::Length,
@@ -72,23 +68,31 @@ async fn length_tool_call_and_stop_marker_over_real_grpc() {
let events = sse_events(&text);
assert_one_terminal(&events);
assert_eq!(events.last().unwrap()["type"], "response.incomplete");
}
/// The markup of one tool call, cut into 9-character pieces as an engine streams it.
fn tool_call_pieces() -> Vec<String> {
let markup = "<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>";
let pieces: Vec<String> = markup
markup
.chars()
.collect::<Vec<_>>()
.chunks(9)
.map(|c| c.iter().collect())
.collect();
.collect()
}
fn lookup_tool_declaration() -> Value {
let parameters = json!({"type": "object", "properties": {"key": {"type": "string"}},
"required": ["key"], "additionalProperties": false});
json!({"tools": [{"type": "function", "name": "lookup", "parameters": parameters}]})
}
async fn tool_call_markup_becomes_a_function_call(runtime: &Runtime, stack: &Stack) {
let pieces = tool_call_pieces();
let refs: Vec<&str> = pieces.iter().map(String::as_str).collect();
runtime.engine.push(Script::stop_with(&refs, usage(30, 20)));
let (status, text) = stack
.post(
"/v1/responses",
&body(json!({"tools": [{"type": "function", "name": "lookup",
"parameters": {"type": "object", "properties": {"key": {"type": "string"}},
"required": ["key"], "additionalProperties": false}}]})),
)
.post("/v1/responses", &body(lookup_tool_declaration()))
.await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
@@ -103,6 +107,14 @@ async fn length_tool_call_and_stop_marker_over_real_grpc() {
serde_json::from_str::<Value>(call["arguments"].as_str().unwrap()).unwrap(),
json!({"key": "value"})
);
}
#[tokio::test(flavor = "multi_thread")]
async fn length_tool_call_and_stop_marker_over_real_grpc() {
let (runtime, stack) = ready("chain-finish").await;
length_finish_is_incomplete(&runtime, &stack).await;
tool_call_markup_becomes_a_function_call(&runtime, &stack).await;
// The model ends its turn with a marker; the engine would keep going, the marker stops it.
runtime
+45 -53
View File
@@ -1,35 +1,18 @@
//! Explicit failures: auth, saturation, interruption, binding and disconnect quarantine.
use crate::harness::{Counting, TOKEN, config, held, request, server, status, wait_started};
use crate::harness::{
Counting, Server, TOKEN, config, gateway_server, held_server, request, server, status,
wait_one_queued, wait_started,
};
use axum::body::{Body, Bytes};
use axum::routing::post;
use axum::{Json, Router};
use futures_util::StreamExt;
use serde_json::json;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::time::Duration;
use strata_desktop_core::gateway::Gateway;
use tokio::sync::{Notify, Semaphore};
#[tokio::test]
async fn auth_capabilities_and_queue_saturation_fail_explicitly() {
let c = Arc::new(Counting {
started: AtomicUsize::new(0),
notify: Notify::new(),
release: Semaphore::new(0),
});
let a = server(
Router::new()
.route("/v1/responses", post(held))
.with_state(c.clone()),
)
.await;
let mut cfg = config(&[&a]);
cfg.queue_limit = 1;
cfg.queue_timeout_ms = 100;
let g = server(Gateway::with_token(cfg, TOKEN.into()).unwrap().router()).await;
let client = reqwest::Client::new();
async fn refuses_missing_token_and_unsupported_input(client: &reqwest::Client, g: &Server) {
assert_eq!(
client
.get(format!("{}/v1/models", g.url))
@@ -41,8 +24,8 @@ async fn auth_capabilities_and_queue_saturation_fail_explicitly() {
);
assert_eq!(
request(
&client,
&g,
client,
g,
json!({"model":"pool","input":[{"type":"input_image","image_url":"x"}]})
)
.send()
@@ -51,18 +34,24 @@ async fn auth_capabilities_and_queue_saturation_fail_explicitly() {
.status(),
409
);
}
#[tokio::test]
async fn auth_capabilities_and_queue_saturation_fail_explicitly() {
let c = Counting::shared();
let a = held_server(&c).await;
let mut cfg = config(&[&a]);
cfg.queue_limit = 1;
cfg.queue_timeout_ms = 100;
let g = gateway_server(cfg).await;
let client = reqwest::Client::new();
refuses_missing_token_and_unsupported_input(&client, &g).await;
let r = request(&client, &g, json!({"model":"d0","input":"hold"}));
let hold = tokio::spawn(async move { r.send().await.unwrap() });
wait_started(&c, 1).await;
let r = request(&client, &g, json!({"model":"d0","input":"wait"}));
let wait = tokio::spawn(async move { r.send().await.unwrap() });
tokio::time::timeout(Duration::from_secs(1), async {
while status(&client, &g).await["pool"]["queued"] != 1 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
wait_one_queued(&client, &g).await;
assert_eq!(
request(&client, &g, json!({"model":"d0","input":"overflow"}))
.send()
@@ -76,9 +65,8 @@ async fn auth_capabilities_and_queue_saturation_fail_explicitly() {
assert_eq!(hold.await.unwrap().status(), 200);
}
#[tokio::test]
async fn interrupted_upstream_is_quarantined_without_stalling_other_nodes() {
let a = server(Router::new().route(
async fn created_only_upstream() -> Server {
server(Router::new().route(
"/v1/responses",
post(|| async {
(
@@ -87,18 +75,22 @@ async fn interrupted_upstream_is_quarantined_without_stalling_other_nodes() {
)
}),
))
.await;
let b = server(Router::new().route(
.await
}
async fn healthy_upstream() -> Server {
server(Router::new().route(
"/v1/responses",
post(|| async { Json(json!({"id":"healthy","status":"completed"})) }),
))
.await;
let g = server(
Gateway::with_token(config(&[&a, &b]), TOKEN.into())
.unwrap()
.router(),
)
.await;
.await
}
#[tokio::test]
async fn interrupted_upstream_is_quarantined_without_stalling_other_nodes() {
let a = created_only_upstream().await;
let b = healthy_upstream().await;
let g = gateway_server(config(&[&a, &b])).await;
let client = reqwest::Client::new();
let r = request(&client, &g, json!({"model":"d0","stream":true,"input":"x"}))
.send()
@@ -132,9 +124,9 @@ async fn rejects_public_endpoint_bind_and_duplicate_endpoints() {
assert!(Gateway::with_token(c, TOKEN.into()).is_err());
}
#[tokio::test]
async fn client_disconnect_quarantines_worker_until_verified_recovery() {
let a = server(Router::new().route(
/// An upstream that sends one event and then hangs.
async fn hanging_upstream() -> Server {
server(Router::new().route(
"/v1/responses",
post(|| async {
let initial = futures_util::stream::once(async {
@@ -148,13 +140,13 @@ async fn client_disconnect_quarantines_worker_until_verified_recovery() {
)
}),
))
.await;
let g = server(
Gateway::with_token(config(&[&a]), TOKEN.into())
.unwrap()
.router(),
)
.await;
.await
}
#[tokio::test]
async fn client_disconnect_quarantines_worker_until_verified_recovery() {
let a = hanging_upstream().await;
let g = gateway_server(config(&[&a])).await;
let client = reqwest::Client::new();
let r = request(&client, &g, json!({"model":"d0","stream":true,"input":"x"}))
.send()
+67 -24
View File
@@ -1,13 +1,14 @@
//! The server, configuration and request builders of the gateway tests.
use axum::extract::State;
use axum::routing::post;
use axum::{Json, Router};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use strata_desktop_core::gateway::{Config, Deployment, Group};
use strata_desktop_core::gateway::{Config, Deployment, Gateway, Group};
use tokio::sync::{Notify, Semaphore};
use tokio::task::JoinHandle;
@@ -41,29 +42,8 @@ pub(super) fn config(nodes: &[&Server]) -> Config {
queue_limit: 2,
queue_timeout_ms: 1000,
request_timeout_ms: 3000,
groups: nodes
.iter()
.enumerate()
.map(|(i, _)| Group {
id: format!("g{i}"),
slots: 1,
available_bytes: 100,
})
.collect(),
deployments: nodes
.iter()
.enumerate()
.map(|(i, n)| Deployment {
id: format!("d{i}"),
model: format!("m{i}"),
endpoint: n.url.clone(),
token_env: None,
group: format!("g{i}"),
slots: 1,
request_bytes: 100,
capabilities: vec!["responses".into(), "tools".into()],
})
.collect(),
groups: groups_for(nodes),
deployments: deployments_for(nodes),
aliases: BTreeMap::from([(
"pool".into(),
(0..nodes.len()).map(|i| format!("d{i}")).collect(),
@@ -71,6 +51,38 @@ pub(super) fn config(nodes: &[&Server]) -> Config {
}
}
fn groups_for(nodes: &[&Server]) -> Vec<Group> {
(0..nodes.len())
.map(|i| Group {
id: format!("g{i}"),
slots: 1,
available_bytes: 100,
})
.collect()
}
fn deployments_for(nodes: &[&Server]) -> Vec<Deployment> {
nodes
.iter()
.enumerate()
.map(|(i, n)| Deployment {
id: format!("d{i}"),
model: format!("m{i}"),
endpoint: n.url.clone(),
token_env: None,
group: format!("g{i}"),
slots: 1,
request_bytes: 100,
capabilities: vec!["responses".into(), "tools".into()],
})
.collect()
}
/// A gateway router over `cfg`, served on a free loopback port.
pub(super) async fn gateway_server(cfg: Config) -> Server {
server(Gateway::with_token(cfg, TOKEN.into()).unwrap().router()).await
}
pub(super) fn request(
client: &reqwest::Client,
g: &Server,
@@ -124,3 +136,34 @@ pub(super) async fn wait_started(c: &Counting, n: usize) {
.await
.unwrap();
}
impl Counting {
pub(super) fn shared() -> Arc<Counting> {
Arc::new(Counting {
started: AtomicUsize::new(0),
notify: Notify::new(),
release: Semaphore::new(0),
})
}
}
/// A node whose `/v1/responses` holds every request until a permit is released.
pub(super) async fn held_server(c: &Arc<Counting>) -> Server {
server(
Router::new()
.route("/v1/responses", post(held))
.with_state(c.clone()),
)
.await
}
/// Waits until exactly one request of the pool is queued.
pub(super) async fn wait_one_queued(client: &reqwest::Client, g: &Server) {
tokio::time::timeout(Duration::from_secs(1), async {
while status(client, g).await["pool"]["queued"] != 1 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
+90 -90
View File
@@ -1,68 +1,22 @@
//! Overlap, queueing, affinity and fragmented SSE.
use crate::harness::{Counting, TOKEN, config, held, request, server, status, wait_started};
use crate::harness::{
Counting, Server, TOKEN, config, gateway_server, held_server, request, server, status,
wait_one_queued, wait_started,
};
use axum::body::{Body, Bytes};
use axum::routing::post;
use axum::{Json, Router};
use serde_json::{Value, json};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use std::sync::atomic::Ordering;
use strata_desktop_core::gateway::Gateway;
use tokio::sync::{Notify, Semaphore};
#[tokio::test]
async fn three_http_requests_overlap_fourth_queues_and_affinity_is_preserved() {
let c = Arc::new(Counting {
started: AtomicUsize::new(0),
notify: Notify::new(),
release: Semaphore::new(0),
});
let a = server(
Router::new()
.route("/v1/responses", post(held))
.with_state(c.clone()),
)
.await;
let b = server(
Router::new()
.route("/v1/responses", post(held))
.with_state(c.clone()),
)
.await;
let d = server(
Router::new()
.route("/v1/responses", post(held))
.with_state(c.clone()),
)
.await;
let gateway = Gateway::with_token(config(&[&a, &b, &d]), TOKEN.into()).unwrap();
let g = server(gateway.router()).await;
let client = reqwest::Client::new();
let mut jobs = Vec::new();
for i in 0..3 {
let r = request(
&client,
&g,
json!({"model":"pool","input":format!("job-{i}")}),
);
jobs.push(tokio::spawn(async move {
r.send().await.unwrap().text().await.unwrap()
}));
}
wait_started(&c, 3).await;
assert_eq!(status(&client, &g).await["pool"]["active"], 3);
let r = request(&client, &g, json!({"model":"pool","input":"fourth"}));
let fourth = tokio::spawn(async move { r.send().await.unwrap().text().await.unwrap() });
tokio::time::timeout(Duration::from_secs(1), async {
while status(&client, &g).await["pool"]["queued"] != 1 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(c.started.load(Ordering::SeqCst), 3);
c.release.add_permits(4);
fn spawn_text(r: reqwest::RequestBuilder) -> tokio::task::JoinHandle<String> {
tokio::spawn(async move { r.send().await.unwrap().text().await.unwrap() })
}
/// Awaits the three overlapping jobs: every answer echoes its job and they ran on three models.
async fn three_distinct_answers(jobs: Vec<tokio::task::JoinHandle<String>>) -> Value {
let mut models = std::collections::HashSet::new();
let mut first = None;
for (i, j) in jobs.into_iter().enumerate() {
@@ -72,12 +26,13 @@ async fn three_http_requests_overlap_fourth_queues_and_affinity_is_preserved() {
first = Some(v);
}
assert_eq!(models.len(), 3);
assert!(fourth.await.unwrap().contains("fourth"));
let old = first.unwrap();
c.release.add_permits(1);
first.unwrap()
}
async fn continuation_keeps_its_worker(client: &reqwest::Client, g: &Server, old: &Value) {
let next = request(
&client,
&g,
client,
g,
json!({"model":"pool","input":"continuation","previous_response_id":old["id"]}),
)
.send()
@@ -86,8 +41,8 @@ async fn three_http_requests_overlap_fourth_queues_and_affinity_is_preserved() {
let next: Value = serde_json::from_str(&next.text().await.unwrap()).unwrap();
assert_eq!(next["model"], old["model"]);
let denied = request(
&client,
&g,
client,
g,
json!({"model":"pool","previous_response_id":"unknown","input":"x"}),
)
.send()
@@ -96,35 +51,80 @@ async fn three_http_requests_overlap_fourth_queues_and_affinity_is_preserved() {
assert_eq!(denied.status(), 409);
}
fn spawn_three_jobs(client: &reqwest::Client, g: &Server) -> Vec<tokio::task::JoinHandle<String>> {
(0..3)
.map(|i| {
let body = json!({"model":"pool","input":format!("job-{i}")});
spawn_text(request(client, g, body))
})
.collect()
}
#[tokio::test]
async fn three_http_requests_overlap_fourth_queues_and_affinity_is_preserved() {
let c = Counting::shared();
let a = held_server(&c).await;
let b = held_server(&c).await;
let d = held_server(&c).await;
let gateway = Gateway::with_token(config(&[&a, &b, &d]), TOKEN.into()).unwrap();
let g = server(gateway.router()).await;
let client = reqwest::Client::new();
let jobs = spawn_three_jobs(&client, &g);
wait_started(&c, 3).await;
assert_eq!(status(&client, &g).await["pool"]["active"], 3);
let fourth = spawn_text(request(
&client,
&g,
json!({"model":"pool","input":"fourth"}),
));
wait_one_queued(&client, &g).await;
assert_eq!(c.started.load(Ordering::SeqCst), 3);
c.release.add_permits(4);
let old = three_distinct_answers(jobs).await;
assert!(fourth.await.unwrap().contains("fourth"));
c.release.add_permits(1);
continuation_keeps_its_worker(&client, &g, &old).await;
}
const FRAGMENTED_WIRE: &str = concat!(
"event: response.output_item.done\n",
"data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"function_call\",\"call_id\":\"c1\",",
"\"name\":\"test\",\"arguments\":\"{\\\"a\\\":1}\"}}\n\n",
"event: response.completed\n",
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"stream-1\",\"status\":\"completed\"}}\n\n"
);
/// An upstream that answers with `FRAGMENTED_WIRE` cut into 3-byte chunks.
async fn fragmented_upstream(Json(v): Json<Value>) -> impl axum::response::IntoResponse {
assert_eq!(v["model"], "m0");
assert_eq!(v["tools"][0]["name"], "test");
let chunks: Vec<_> = FRAGMENTED_WIRE
.as_bytes()
.chunks(3)
.map(Bytes::copy_from_slice)
.map(Ok::<_, std::io::Error>)
.collect();
(
[("content-type", "text/event-stream")],
Body::from_stream(futures_util::stream::iter(chunks)),
)
}
#[tokio::test]
async fn fragmented_sse_tool_arguments_are_byte_identical() {
let wire = "event: response.output_item.done\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"function_call\",\"call_id\":\"c1\",\"name\":\"test\",\"arguments\":\"{\\\"a\\\":1}\"}}\n\nevent: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"stream-1\",\"status\":\"completed\"}}\n\n";
let a = server(Router::new().route(
"/v1/responses",
post(move |Json(v): Json<Value>| async move {
assert_eq!(v["model"], "m0");
assert_eq!(v["tools"][0]["name"], "test");
let chunks: Vec<_> = wire
.as_bytes()
.chunks(3)
.map(Bytes::copy_from_slice)
.map(Ok::<_, std::io::Error>)
.collect();
(
[("content-type", "text/event-stream")],
Body::from_stream(futures_util::stream::iter(chunks)),
)
}),
))
.await;
let g = server(
Gateway::with_token(config(&[&a]), TOKEN.into())
.unwrap()
.router(),
)
.await;
let wire = FRAGMENTED_WIRE;
let a = server(Router::new().route("/v1/responses", post(fragmented_upstream))).await;
let g = gateway_server(config(&[&a])).await;
let client = reqwest::Client::new();
let r=request(&client,&g,json!({"model":"pool","stream":true,"input":"x","tools":[{"type":"function","name":"test","parameters":{"type":"object"}}]})).send().await.unwrap();
let tool = json!({"type":"function","name":"test","parameters":{"type":"object"}});
let r = request(
&client,
&g,
json!({"model":"pool","stream":true,"input":"x","tools":[tool]}),
)
.send()
.await
.unwrap();
assert_eq!(r.headers()["x-strata-deployment"], "d0");
assert_eq!(r.text().await.unwrap(), wire);
let s = status(&client, &g).await;
+15 -10
View File
@@ -1,10 +1,10 @@
//! Key order of the JSON the native adapter turns into prompt text and into the arguments string it hands to a client.
//!
//! The Python Original keeps the order objects were written in (`json.loads`, `tojson` with `sort_keys=False`), so a replayed
//! tool call lists its `<parameter=...>` blocks in the client's order and a call the model wrote comes back with its
//! arguments in the model's order. That needs serde_json's `preserve_order`, which this crate declares itself: a build of this
//! crate alone (`cargo build -p strata-desktop-core`) used to sort the keys, while a build next to `strata-control` (which
//! pulled the feature in through `leleka-harmony`) did not.
//! The Python Original keeps the order objects were written in (`json.loads`, `tojson` with `sort_keys=False`), so a
//! replayed tool call lists its `<parameter=...>` blocks in the client's order and a call the model wrote comes back
//! with its arguments in the model's order. That needs serde_json's `preserve_order`, which this crate declares itself:
//! a build of this crate alone (`cargo build -p strata-desktop-core`) used to sort the keys, while a build next to
//! `strata-control` (which pulled the feature in through `leleka-harmony`) did not.
use serde_json::{Value, json};
use strata_desktop_core::runtime_tools::{ValidatedSegment, prepare};
@@ -29,15 +29,17 @@ fn serde_json_keeps_insertion_order_in_this_build() {
fn replayed_call_arguments_keep_the_order_the_client_wrote() {
let req = json!({"model":"native_fixture","max_output_tokens":64,"tools":[function()],"input":[
{"role":"user","content":"read"},
{"type":"function_call","call_id":"call_1","name":"read","arguments":"{\"zeta\":\"1\",\"alpha\":\"2\"}"},
{"type":"function_call","call_id":"call_1","name":"read",
"arguments":"{\"zeta\":\"1\",\"alpha\":\"2\"}"},
{"type":"function_call_output","call_id":"call_1","output":"done"},
{"role":"user","content":"continue"}
]});
let prompt = prepare(&req).unwrap().prompt;
assert!(
prompt.contains("<tool_call>\n<function=read>\n<parameter=zeta>\n1\n</parameter>\n<parameter=alpha>\n2\n</parameter>\n</function>\n</tool_call>"),
"{prompt}"
let expected = concat!(
"<tool_call>\n<function=read>\n<parameter=zeta>\n1\n</parameter>\n",
"<parameter=alpha>\n2\n</parameter>\n</function>\n</tool_call>"
);
assert!(prompt.contains(expected), "{prompt}");
}
#[test]
@@ -46,7 +48,10 @@ fn a_call_the_model_wrote_returns_its_arguments_in_the_model_order() {
&json!({"model":"native_fixture","input":"x","max_output_tokens":64,"tools":[function()]}),
)
.unwrap();
let text = "<tool_call><function=read><parameter=zeta>1</parameter><parameter=alpha>2</parameter></function></tool_call>";
let text = concat!(
"<tool_call><function=read><parameter=zeta>1</parameter>",
"<parameter=alpha>2</parameter></function></tool_call>"
);
let segments = plan.policy.parse_output(text).unwrap();
let ValidatedSegment::Call(item) = &segments[0] else {
panic!("expected a call");
+55 -52
View File
@@ -23,25 +23,28 @@ async fn finish(m: &Manager, c: WorkerCommand) -> WorkerOperation {
.unwrap()
}
#[tokio::test]
async fn grpc_owned_start_stop_and_exact_response() {
let server = serve(profile("test").await).await;
let mut c = node::connect(server.address).await.unwrap();
type Client = node_client::NodeClient<tonic::transport::Channel>;
fn synthetic_input() -> ResponseRequest {
ResponseRequest {
json: br#"{"model":"fixture","input":"synthetic","stream":false}"#.to_vec(),
}
}
async fn phase(c: &mut Client) -> String {
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.phase
}
async fn refused_before_start(c: &mut Client, input: &ResponseRequest) {
assert_eq!(
c.worker_status(Empty {}).await.unwrap_err().code(),
tonic::Code::Unauthenticated
);
assert_eq!(
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.phase,
"stopped"
);
let input = ResponseRequest {
json: br#"{"model":"fixture","input":"synthetic","stream":false}"#.to_vec(),
};
assert_eq!(phase(c).await, "stopped");
assert_eq!(
c.respond(req(input.clone())).await.unwrap_err().code(),
tonic::Code::Unavailable
@@ -52,22 +55,10 @@ async fn grpc_owned_start_stop_and_exact_response() {
c.control_worker(req(stale)).await.unwrap_err().code(),
tonic::Code::FailedPrecondition
);
assert_eq!(
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.phase,
"stopped"
);
let op = command(1, 0);
assert_eq!(remote_finish(&mut c, op.clone()).await.status, "succeeded");
let state = c.worker_status(req(Empty {})).await.unwrap().into_inner();
assert_eq!(state.phase, "ready");
assert_ne!(state.pid, 0);
// Same operation ID survives transport disconnect without spawning twice.
drop(c);
let mut c = node::connect(server.address).await.unwrap();
assert_eq!(phase(c).await, "stopped");
}
async fn operation_survives_reconnect(c: &mut Client, op: WorkerCommand, pid: u32) {
assert_eq!(
c.control_worker(req(op.clone()))
.await
@@ -82,7 +73,7 @@ async fn grpc_owned_start_stop_and_exact_response() {
.unwrap()
.into_inner()
.pid,
state.pid
pid
);
let mut conflict = op;
conflict.action = 2;
@@ -90,6 +81,9 @@ async fn grpc_owned_start_stop_and_exact_response() {
c.control_worker(req(conflict)).await.unwrap_err().code(),
tonic::Code::AlreadyExists
);
}
async fn exact_streamed_response(c: &mut Client, input: &ResponseRequest) {
let mut frames = c.respond(req(input.clone())).await.unwrap().into_inner();
let mut data = vec![];
let mut end = false;
@@ -102,26 +96,19 @@ async fn grpc_owned_start_stop_and_exact_response() {
}
assert_eq!(data, OUTPUT.as_bytes());
assert!(end);
assert_eq!(
remote_finish(&mut c, command(2, 1000)).await.status,
"succeeded"
);
assert_eq!(
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.phase,
"stopped"
);
}
async fn stop_refuses_then_restart_conflicts_on_old_response(
c: &mut Client,
input: ResponseRequest,
) {
assert_eq!(remote_finish(c, command(2, 1000)).await.status, "succeeded");
assert_eq!(phase(c).await, "stopped");
assert_eq!(
c.respond(req(input)).await.unwrap_err().code(),
tonic::Code::Unavailable
);
assert_eq!(
remote_finish(&mut c, command(1, 0)).await.status,
"succeeded"
);
assert_eq!(remote_finish(c, command(1, 0)).await.status, "succeeded");
let mut old = c
.respond(req(ResponseRequest {
json:
@@ -139,10 +126,26 @@ async fn grpc_owned_start_stop_and_exact_response() {
}))
));
drop(old);
assert_eq!(
remote_finish(&mut c, command(2, 1000)).await.status,
"succeeded"
);
assert_eq!(remote_finish(c, command(2, 1000)).await.status, "succeeded");
}
#[tokio::test]
async fn grpc_owned_start_stop_and_exact_response() {
let server = serve(profile("test").await).await;
let mut c = node::connect(server.address).await.unwrap();
let input = synthetic_input();
refused_before_start(&mut c, &input).await;
let op = command(1, 0);
assert_eq!(remote_finish(&mut c, op.clone()).await.status, "succeeded");
let state = c.worker_status(req(Empty {})).await.unwrap().into_inner();
assert_eq!(state.phase, "ready");
assert_ne!(state.pid, 0);
// Same operation ID survives transport disconnect without spawning twice.
drop(c);
let mut c = node::connect(server.address).await.unwrap();
operation_survives_reconnect(&mut c, op, state.pid).await;
exact_streamed_response(&mut c, &input).await;
stop_refuses_then_restart_conflicts_on_old_response(&mut c, input).await;
}
#[tokio::test]
+45 -40
View File
@@ -6,6 +6,50 @@ use crate::harness::OUTPUT;
use std::time::Duration;
use tokio::net::TcpListener;
fn fixture_router(model: String) -> axum::Router {
let health_model = if model == "wrong" {
"unexpected".to_string()
} else {
model.clone()
};
axum::Router::new()
.route(
"/health",
axum::routing::get(move || {
let model = health_model.clone();
async move { axum::Json(serde_json::json!({"status":"ok","loaded":true,"model":model})) }
}),
)
.route("/v1/responses", axum::routing::post(responses_route(model == "slow")))
.route("/exit", axum::routing::get(exit_route))
}
fn responses_route(slow: bool) -> axum::routing::MethodRouter {
if slow {
axum::routing::post(respond_slowly)
} else {
axum::routing::post(respond_at_once)
}
}
async fn respond_slowly() -> impl axum::response::IntoResponse {
tokio::time::sleep(Duration::from_millis(600)).await;
respond_at_once().await
}
async fn respond_at_once() -> impl axum::response::IntoResponse {
(
[(axum::http::header::CONTENT_TYPE, "application/json")],
OUTPUT,
)
}
async fn exit_route() -> &'static str {
std::process::exit(7);
#[allow(unreachable_code)]
"exited"
}
// Same Rust test executable becomes a real isolated backend child. No Python,
// GPU, model download, request capture or running user endpoint is involved.
#[test]
@@ -21,46 +65,7 @@ fn fixture() {
.build()
.unwrap()
.block_on(async move {
let health_model = if model == "wrong" {
"unexpected".to_string()
} else {
model.clone()
};
let router = axum::Router::new()
.route(
"/health",
axum::routing::get(move || {
let model = health_model.clone();
async move {
axum::Json(
serde_json::json!({"status":"ok","loaded":true,"model":model}),
)
}
}),
)
.route(
"/v1/responses",
axum::routing::post(move || {
let slow = model == "slow";
async move {
if slow {
tokio::time::sleep(Duration::from_millis(600)).await;
}
(
[(axum::http::header::CONTENT_TYPE, "application/json")],
OUTPUT,
)
}
}),
)
.route(
"/exit",
axum::routing::get(|| async {
std::process::exit(7);
#[allow(unreachable_code)]
"exited"
}),
);
let router = fixture_router(model);
axum::serve(TcpListener::bind(endpoint).await.unwrap(), router)
.await
.unwrap();
+103 -80
View File
@@ -6,16 +6,10 @@ use strata_desktop_core::node::proto::*;
use strata_desktop_core::node::{self};
use tokio::net::TcpListener;
#[tokio::test]
async fn stop_timeout_does_not_kill_active_request() {
let server = serve(profile("slow").await).await;
let mut c = node::connect(server.address).await.unwrap();
assert_eq!(
remote_finish(&mut c, command(1, 0)).await.status,
"succeeded"
);
let mut response_client = c.clone();
let request = tokio::spawn(async move {
type Client = strata_desktop_core::node::proto::node_client::NodeClient<tonic::transport::Channel>;
fn spawn_slow_request(mut response_client: Client) -> tokio::task::JoinHandle<Vec<u8>> {
tokio::spawn(async move {
let mut stream = response_client
.respond(req(ResponseRequest {
json: br#"{"model":"fixture","input":"synthetic","stream":false}"#.to_vec(),
@@ -30,7 +24,10 @@ async fn stop_timeout_does_not_kill_active_request() {
}
}
data
});
})
}
async fn wait_for_one_active_response(c: &mut Client) {
tokio::time::timeout(Duration::from_secs(2), async {
loop {
if c.handshake(req(Hello {
@@ -49,6 +46,18 @@ async fn stop_timeout_does_not_kill_active_request() {
})
.await
.unwrap();
}
#[tokio::test]
async fn stop_timeout_does_not_kill_active_request() {
let server = serve(profile("slow").await).await;
let mut c = node::connect(server.address).await.unwrap();
assert_eq!(
remote_finish(&mut c, command(1, 0)).await.status,
"succeeded"
);
let request = spawn_slow_request(c.clone());
wait_for_one_active_response(&mut c).await;
// Give the request time to acquire its lease before draining.
tokio::time::sleep(Duration::from_millis(50)).await;
assert_eq!(
@@ -70,18 +79,19 @@ async fn stop_timeout_does_not_kill_active_request() {
);
}
#[tokio::test]
async fn cli_profile_start_status_stop_and_node_drop_cleanup() {
use tokio::io::{AsyncBufReadExt, BufReader};
let p = profile("test").await;
let path = std::env::temp_dir().join(format!("strata-profile-{}.json", uuid::Uuid::new_v4()));
struct FileGuard(std::path::PathBuf);
impl Drop for FileGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
struct FileGuard(std::path::PathBuf);
impl Drop for FileGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
let _file = FileGuard(path.clone());
}
fn write_profile_file(
p: &strata_desktop_core::managed_worker::Profile,
) -> (std::path::PathBuf, FileGuard) {
let path = std::env::temp_dir().join(format!("strata-profile-{}.json", uuid::Uuid::new_v4()));
let guard = FileGuard(path.clone());
std::fs::write(
&path,
serde_json::to_vec(&serde_json::json!({
@@ -91,6 +101,10 @@ async fn cli_profile_start_status_stop_and_node_drop_cleanup() {
.unwrap(),
)
.unwrap();
(path, guard)
}
async fn spawn_node(path: &std::path::Path) -> (tokio::process::Child, String) {
let mut node = tokio::process::Command::new(env!("CARGO_BIN_EXE_strata-desktop"))
.args([
"node",
@@ -100,70 +114,91 @@ async fn cli_profile_start_status_stop_and_node_drop_cleanup() {
"STRATA_NODE_TOKEN",
"--worker-profile",
])
.arg(&path)
.arg(path)
.env("STRATA_NODE_TOKEN", TOKEN)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.kill_on_drop(true)
.spawn()
.unwrap();
let address = read_listen_address(&mut node).await;
(node, address)
}
/// The address the node prints on its first stdout line.
async fn read_listen_address(node: &mut tokio::process::Child) -> String {
use tokio::io::{AsyncBufReadExt, BufReader};
let mut lines = BufReader::new(node.stdout.take().unwrap()).lines();
let line = tokio::time::timeout(Duration::from_secs(5), lines.next_line())
.await
.unwrap()
.unwrap()
.unwrap();
let address = serde_json::from_str::<serde_json::Value>(&line).unwrap()["endpoint"]
serde_json::from_str::<serde_json::Value>(&line).unwrap()["endpoint"]
.as_str()
.unwrap()
.trim_start_matches("http://")
.to_string();
async fn cli(address: &str, action: &[&str]) -> serde_json::Value {
let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_strata-desktop"));
command
.args([
"worker",
"--node",
address,
"--token-env",
"STRATA_NODE_TOKEN",
])
.args(action)
.env("STRATA_NODE_TOKEN", TOKEN)
.kill_on_drop(true);
let output = tokio::time::timeout(Duration::from_secs(5), command.output())
.await
.unwrap()
.unwrap();
assert!(output.status.success(), "CLI action failed");
serde_json::from_slice(&output.stdout).unwrap()
.to_string()
}
async fn cli(address: &str, action: &[&str]) -> serde_json::Value {
let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_strata-desktop"));
command
.args([
"worker",
"--node",
address,
"--token-env",
"STRATA_NODE_TOKEN",
])
.args(action)
.env("STRATA_NODE_TOKEN", TOKEN)
.kill_on_drop(true);
let output = tokio::time::timeout(Duration::from_secs(5), command.output())
.await
.unwrap()
.unwrap();
assert!(output.status.success(), "CLI action failed");
serde_json::from_slice(&output.stdout).unwrap()
}
fn epoch_command(
operation_id: String,
action: i32,
drain_timeout_ms: u32,
expected_epoch: &str,
) -> WorkerCommand {
WorkerCommand {
operation_id,
action,
drain_timeout_ms,
expected_epoch: expected_epoch.to_string(),
}
}
async fn node_epoch(c: &mut Client) -> String {
let hello = Hello {
protocol_version: 1,
};
c.handshake(req(hello))
.await
.unwrap()
.into_inner()
.agent_epoch
}
#[tokio::test]
async fn cli_profile_start_status_stop_and_node_drop_cleanup() {
let p = profile("test").await;
let (path, _file) = write_profile_file(&p);
let (mut node, address) = spawn_node(&path).await;
assert_eq!(cli(&address, &["status"]).await["phase"], "stopped");
let id = uuid::Uuid::new_v4().to_string();
assert_eq!(cli(&address, &["start", &id]).await["operation_id"], id);
let mut c = node::connect(address.parse().unwrap()).await.unwrap();
let epoch = c
.handshake(req(Hello {
protocol_version: 1,
}))
.await
.unwrap()
.into_inner()
.agent_epoch;
assert_eq!(
remote_finish(
&mut c,
WorkerCommand {
operation_id: id.clone(),
action: 1,
drain_timeout_ms: 0,
expected_epoch: epoch.clone(),
}
)
.await
.status,
"succeeded"
);
let epoch = node_epoch(&mut c).await;
let start = epoch_command(id.clone(), 1, 0, &epoch);
assert_eq!(remote_finish(&mut c, start).await.status, "succeeded");
assert_eq!(
cli(&address, &["operation", &id]).await["status"],
"succeeded"
@@ -171,20 +206,8 @@ async fn cli_profile_start_status_stop_and_node_drop_cleanup() {
assert_eq!(cli(&address, &["status"]).await["phase"], "ready");
let id = uuid::Uuid::new_v4().to_string();
cli(&address, &["stop", &id]).await;
assert_eq!(
remote_finish(
&mut c,
WorkerCommand {
operation_id: id,
action: 2,
drain_timeout_ms: 30000,
expected_epoch: epoch.clone(),
}
)
.await
.status,
"succeeded"
);
let stop = epoch_command(id, 2, 30000, &epoch);
assert_eq!(remote_finish(&mut c, stop).await.status, "succeeded");
node.kill().await.unwrap();
node.wait().await.unwrap();
assert!(TcpListener::bind(p.endpoint).await.is_ok());
+22 -14
View File
@@ -115,6 +115,27 @@ fn mtp_missing_or_future_selection_cannot_fall_back_to_native() {
}
}
fn assert_substituted_modes_refused(
matching: &LoadedModel,
requested: &RuntimeConfig,
opposite: &str,
) {
for substituted in [
InferenceMode::Native,
InferenceMode::ExperimentalKarPle {
profile_id: "qwen-iq3-s-l2-v4-ple".into(),
},
mode(opposite),
] {
let mut different = matching.clone();
different.effective_mode = substituted;
assert_eq!(
different.validate_for_load(&descriptor(), requested),
Err(ContractError::InvalidField("loaded_inference_mode"))
);
}
}
#[test]
fn mtp_loaded_effective_profile_cannot_be_substituted_or_silently_disabled() {
for requested_profile in [NATIVE_MTP, KAR_MTP] {
@@ -140,20 +161,7 @@ fn mtp_loaded_effective_profile_cannot_be_substituted_or_silently_disabled() {
} else {
NATIVE_MTP
};
for substituted in [
InferenceMode::Native,
InferenceMode::ExperimentalKarPle {
profile_id: "qwen-iq3-s-l2-v4-ple".into(),
},
mode(opposite),
] {
let mut different = matching.clone();
different.effective_mode = substituted;
assert_eq!(
different.validate_for_load(&descriptor(), &requested),
Err(ContractError::InvalidField("loaded_inference_mode"))
);
}
assert_substituted_modes_refused(&matching, &requested, opposite);
}
}
@@ -133,61 +133,73 @@ impl api::Backend for Synthetic {
};
let (sink, stream) = api::GenerationSink::bounded_channel(4).unwrap();
let behavior = self.behavior;
let worker = std::thread::spawn(move || {
// MissingTerminal deliberately drops an accepted producer without a terminal.
if matches!(behavior, Behavior::MissingTerminal) {
return;
}
let raw = if matches!(behavior, Behavior::ValidOnly)
|| (matches!(
behavior,
Behavior::InvalidThenValid | Behavior::AggregateOverflow
) && attempt > 0)
{
VALID_RAW
} else {
INVALID_RAW
};
sink.emit(api::GenerationEvent::TextDelta { text: raw.into() })
.unwrap();
if matches!(behavior, Behavior::AcceptedFailure) {
sink.fail(
api::ErrorCode::BackendUnavailable,
"NEVER_PUBLISH_PRIVATE_FAILURE",
true,
)
.unwrap();
} else {
let usage = match behavior {
Behavior::InvalidUsageCached => api::Usage {
input_tokens: 11,
output_tokens: 7,
reused_input_tokens: 12,
},
Behavior::InvalidUsageTotal => api::Usage {
input_tokens: u64::MAX,
output_tokens: 1,
reused_input_tokens: 0,
},
Behavior::AggregateOverflow if attempt == 0 => api::Usage {
input_tokens: u64::MAX,
output_tokens: 0,
reused_input_tokens: 0,
},
_ => api::Usage {
input_tokens: 11,
output_tokens: 7,
reused_input_tokens: 0,
},
};
sink.complete(api::FinishReason::Stop, usage).unwrap();
}
});
let worker = std::thread::spawn(move || script_attempt(sink, behavior, attempt));
self.facts.threads.lock().unwrap().push(worker);
Ok(stream)
}
}
/// What the generation thread emits for the `attempt`-th request of one scripted behavior.
fn script_attempt(sink: api::GenerationSink, behavior: Behavior, attempt: usize) {
// MissingTerminal deliberately drops an accepted producer without a terminal.
if matches!(behavior, Behavior::MissingTerminal) {
return;
}
sink.emit(api::GenerationEvent::TextDelta {
text: scripted_raw(behavior, attempt).into(),
})
.unwrap();
if matches!(behavior, Behavior::AcceptedFailure) {
sink.fail(
api::ErrorCode::BackendUnavailable,
"NEVER_PUBLISH_PRIVATE_FAILURE",
true,
)
.unwrap();
} else {
sink.complete(api::FinishReason::Stop, scripted_usage(behavior, attempt))
.unwrap();
}
}
fn scripted_raw(behavior: Behavior, attempt: usize) -> &'static str {
if matches!(behavior, Behavior::ValidOnly)
|| (matches!(
behavior,
Behavior::InvalidThenValid | Behavior::AggregateOverflow
) && attempt > 0)
{
VALID_RAW
} else {
INVALID_RAW
}
}
fn scripted_usage(behavior: Behavior, attempt: usize) -> api::Usage {
match behavior {
Behavior::InvalidUsageCached => api::Usage {
input_tokens: 11,
output_tokens: 7,
reused_input_tokens: 12,
},
Behavior::InvalidUsageTotal => api::Usage {
input_tokens: u64::MAX,
output_tokens: 1,
reused_input_tokens: 0,
},
Behavior::AggregateOverflow if attempt == 0 => api::Usage {
input_tokens: u64::MAX,
output_tokens: 0,
reused_input_tokens: 0,
},
_ => api::Usage {
input_tokens: 11,
output_tokens: 7,
reused_input_tokens: 0,
},
}
}
pub(super) struct Fixture {
pub(super) base: String,
pub(super) http: reqwest::Client,
@@ -212,42 +224,14 @@ impl Fixture {
let facts = Arc::new(Facts::default());
let rpc = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = rpc.local_addr().unwrap();
let server = RuntimeServer::new(
Box::new(Synthetic {
facts: facts.clone(),
behavior,
}),
TOKEN.into(),
)
.unwrap();
let runtime = tokio::spawn(async move {
server.serve(rpc, std::future::pending()).await.unwrap();
});
let runtime = spawn_runtime_server(rpc, facts.clone(), behavior);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let listen = listener.local_addr().unwrap();
let registry = Registry::new(Config {
schema_version: 1,
listen,
token_env: ENV.into(),
http_pool: None,
experimental_native_tools: experimental,
runtimes: vec![Member {
id: "native_fixture".into(),
address,
token_env: ENV.into(),
artifact_digest: descriptor().artifact_digest,
}],
})
.unwrap();
let daemon = tokio::spawn(async move {
axum::serve(listener, registry.router()).await.unwrap();
});
let registry = registry_for(listen, address, experimental);
let daemon = serve_registry(listener, registry);
let fixture = Self {
base: format!("http://{listen}"),
http: reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.build()
.unwrap(),
http: http_client(5),
facts,
tasks: vec![runtime, daemon],
};
@@ -276,7 +260,12 @@ impl Fixture {
.await
.map(|text| serde_json::from_str(&text).unwrap())
.unwrap();
let command = json!({"model":"native_fixture","operation_id":uuid::Uuid::new_v4().to_string(),"epoch":snapshot["runtimes"][0]["epoch"],"mode":"native"});
let command = json!({
"model": "native_fixture",
"operation_id": uuid::Uuid::new_v4().to_string(),
"epoch": snapshot["runtimes"][0]["epoch"],
"mode": "native",
});
assert_eq!(
self.post("/runtime/load", command.clone())
.await
@@ -284,7 +273,14 @@ impl Fixture {
.as_u16(),
200
);
let query = json!({"model":command["model"],"operation_id":command["operation_id"],"epoch":command["epoch"]});
self.wait_for_loaded(&command).await;
}
async fn wait_for_loaded(&self, command: &Value) {
let query = json!({
"model": command["model"],
"operation_id": command["operation_id"],
"epoch": command["epoch"],
});
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
loop {
let outcome: Value = self
@@ -303,12 +299,63 @@ impl Fixture {
}
}
pub(super) async fn response(&self, stream: bool) -> reqwest::Response {
self.post("/v1/responses",json!({"model":"native_fixture","input":"synthetic read",
"tools":[{"type":"function","name":"read","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"],"additionalProperties":false}}],
"tool_choice":"required","max_output_tokens":32,"stream":stream})).await
let read = json!({"type": "function", "name": "read", "parameters": {
"type": "object", "properties": {"path": {"type": "string"}},
"required": ["path"], "additionalProperties": false}});
self.post(
"/v1/responses",
json!({"model": "native_fixture", "input": "synthetic read", "tools": [read],
"tool_choice": "required", "max_output_tokens": 32, "stream": stream}),
)
.await
}
}
fn spawn_runtime_server(
rpc: tokio::net::TcpListener,
facts: Arc<Facts>,
behavior: Behavior,
) -> JoinHandle<()> {
let server = RuntimeServer::new(Box::new(Synthetic { facts, behavior }), TOKEN.into()).unwrap();
tokio::spawn(async move {
server.serve(rpc, std::future::pending()).await.unwrap();
})
}
fn registry_for(
listen: std::net::SocketAddr,
address: std::net::SocketAddr,
experimental: bool,
) -> Registry {
Registry::new(Config {
schema_version: 1,
listen,
token_env: ENV.into(),
http_pool: None,
experimental_native_tools: experimental,
runtimes: vec![Member {
id: "native_fixture".into(),
address,
token_env: ENV.into(),
artifact_digest: descriptor().artifact_digest,
}],
})
.unwrap()
}
fn serve_registry(listener: tokio::net::TcpListener, registry: Registry) -> JoinHandle<()> {
tokio::spawn(async move {
axum::serve(listener, registry.router()).await.unwrap();
})
}
fn http_client(seconds: u64) -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(seconds))
.build()
.unwrap()
}
pub(super) fn sse(text: &str) -> Vec<Value> {
text.split("\n\n")
.filter_map(|record| record.lines().find_map(|line| line.strip_prefix("data: ")))
@@ -1,6 +1,7 @@
//! The native tool retry: fresh identities, one public response and no replay after acceptance.
use crate::harness::{Behavior, Fixture, credential_child, sse};
use leleka_backend_api as api;
use serde_json::{Value, json};
fn assert_public_sequence(events: &[Value], id: &str) {
@@ -17,6 +18,41 @@ fn assert_public_sequence(events: &[Value], id: &str) {
);
}
fn count_of(events: &[Value], kind: &str) -> usize {
events.iter().filter(|e| e["type"] == kind).count()
}
fn assert_two_fresh_identical_requests(observed: &[api::GenerationRequest]) {
assert_eq!(observed.len(), 2);
assert_ne!(observed[0].request_id, observed[1].request_id);
for request in observed.iter() {
uuid::Uuid::parse_str(&request.request_id).unwrap();
}
assert_eq!(observed[0].prompt, observed[1].prompt);
assert_eq!(observed[0].max_output_tokens, observed[1].max_output_tokens);
}
fn assert_single_function_call_terminal(events: &[Value], id: &str) {
let terminal = &events.last().unwrap()["response"];
assert_eq!(terminal["id"], id);
assert_eq!(terminal["status"], "completed");
assert_eq!(terminal["output"].as_array().unwrap().len(), 1);
let call = &terminal["output"][0];
assert_eq!(call["type"], "function_call");
assert_eq!(call["name"], "read");
assert_eq!(
serde_json::from_str::<Value>(call["arguments"].as_str().unwrap()).unwrap(),
json!({"path":"fixture"})
);
assert_eq!(count_of(events, "response.output_item.added"), 1);
assert!(
events
.iter()
.filter(|e| e["type"] == "response.output_item.added")
.all(|e| e["item"]["call_id"] == call["call_id"])
);
}
#[tokio::test]
async fn completed_invalid_then_valid_uses_two_fresh_ids_one_public_response() {
if credential_child(
@@ -33,53 +69,12 @@ async fn completed_invalid_then_valid_uses_two_fresh_ids_one_public_response() {
assert!(!raw.contains("response.output_text.delta"));
let events = sse(&raw);
let observed = f.facts.requests.lock().unwrap();
assert_eq!(observed.len(), 2);
assert_ne!(observed[0].request_id, observed[1].request_id);
for request in observed.iter() {
uuid::Uuid::parse_str(&request.request_id).unwrap();
}
assert_eq!(observed[0].prompt, observed[1].prompt);
assert_eq!(observed[0].max_output_tokens, observed[1].max_output_tokens);
assert_two_fresh_identical_requests(&observed);
let id = format!("resp_{}", observed[0].request_id.replace('-', ""));
assert_public_sequence(&events, &id);
assert_eq!(
events
.iter()
.filter(|e| e["type"] == "response.completed")
.count(),
1
);
assert_eq!(
events
.iter()
.filter(|e| e["type"] == "response.failed")
.count(),
0
);
let terminal = &events.last().unwrap()["response"];
assert_eq!(terminal["id"], id);
assert_eq!(terminal["status"], "completed");
assert_eq!(terminal["output"].as_array().unwrap().len(), 1);
let call = &terminal["output"][0];
assert_eq!(call["type"], "function_call");
assert_eq!(call["name"], "read");
assert_eq!(
serde_json::from_str::<Value>(call["arguments"].as_str().unwrap()).unwrap(),
json!({"path":"fixture"})
);
assert_eq!(
events
.iter()
.filter(|e| e["type"] == "response.output_item.added")
.count(),
1
);
assert!(
events
.iter()
.filter(|e| e["type"] == "response.output_item.added")
.all(|e| e["item"]["call_id"] == call["call_id"])
);
assert_eq!(count_of(&events, "response.completed"), 1);
assert_eq!(count_of(&events, "response.failed"), 0);
assert_single_function_call_terminal(&events, &id);
}
#[tokio::test]
@@ -1,9 +1,24 @@
//! Call identity, result gating, parallel history and refusal of bad output.
use crate::harness::{call, function, request};
use serde_json::json;
use serde_json::{Value, json};
use strata_desktop_core::runtime_tools::{ValidatedSegment, prepare};
fn assert_regex_input_is_gated(plan: &strata_desktop_core::runtime_tools::ToolPlan, alias: &str) {
for raw in ["move 12", "MOVE 12 trailing", "", "MOVE\n12"] {
assert!(
plan.policy
.parse_output(&call(alias, &[("input", raw)]))
.is_err()
);
}
assert!(
plan.policy
.parse_output(&call("run", &[("input", "MOVE 12")]))
.is_err()
);
}
#[test]
fn namespaced_custom_regex_restores_exact_identity_and_input() {
// Independently frozen SHA256("ops/run")[0..24], not obtained from Catalog.
@@ -23,26 +38,19 @@ fn namespaced_custom_regex_restores_exact_identity_and_input() {
item,
&json!({"type":"custom_tool_call","name":"run","namespace":"ops","input":"MOVE 12"})
);
for raw in ["move 12", "MOVE 12 trailing", "", "MOVE\n12"] {
assert!(
plan.policy
.parse_output(&call(ALIAS, &[("input", raw)]))
.is_err()
);
}
assert!(
plan.policy
.parse_output(&call("run", &[("input", "MOVE 12")]))
.is_err()
);
assert_regex_input_is_gated(&plan, ALIAS);
assert_forced_choice_needs_the_namespace(&req, ALIAS);
}
fn assert_forced_choice_needs_the_namespace(req: &Value, alias: &str) {
let mut forced = req.clone();
forced["tool_choice"] = json!({"type":"custom","name":"run","namespace":"ops"});
let forced_plan = prepare(&forced).unwrap();
assert!(
forced_plan
.policy
.parse_output(&call(ALIAS, &[("input", "MOVE 12")]))
.parse_output(&call(alias, &[("input", "MOVE 12")]))
.is_ok()
);
forced["tool_choice"] = json!({"type":"custom","name":"run"});
@@ -52,7 +60,8 @@ fn namespaced_custom_regex_restores_exact_identity_and_input() {
#[test]
fn exact_call_result_ids_type_and_order_gate_continuation() {
let mut req = request(vec![function("read")]);
let prior = json!({"type":"function_call","call_id":"call_fixture","name":"read","arguments":"{\"path\":\"fixture\"}"});
let prior = json!({"type":"function_call","call_id":"call_fixture","name":"read",
"arguments":"{\"path\":\"fixture\"}"});
let result = json!({"type":"function_call_output","call_id":"call_fixture","output":"owned synthetic result"});
req["input"] =
json!([{"role":"user","content":"read"},prior,result,{"role":"user","content":"continue"}]);
@@ -12,29 +12,11 @@ fn no_tool_prompt_retains_literal_template_bytes() {
plan.prompt,
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
);
assert!(
matches!(&plan.policy.parse_output("plain text").unwrap()[0], ValidatedSegment::Text(text) if text == "plain text")
);
let segments = plan.policy.parse_output("plain text").unwrap();
assert!(matches!(&segments[0], ValidatedSegment::Text(text) if text == "plain text"));
}
#[test]
fn declarations_are_bounded_unique_and_closed_before_render() {
let valid = prepare(&request(vec![function("read")])).unwrap();
assert_eq!(valid.max_output_tokens, 64);
assert!(valid.prompt.contains("read"));
for tools in [
vec![function("read"), function("read")],
vec![json!({"type":"web_search"})],
vec![
json!({"type":"custom","name":"run","format":{"type":"grammar","syntax":"lark","definition":"start: WORD"}}),
],
vec![
json!({"type":"function","name":"read","parameters":{"type":"object"},"surprise":true}),
],
(0..129).map(|i| function(&format!("read_{i}"))).collect(),
] {
assert!(prepare(&request(tools)).is_err());
}
fn assert_invalid_top_level_fields_refused() {
for (field, value) in [
("previous_response_id", json!("resp_old")),
("store", json!(true)),
@@ -46,6 +28,26 @@ fn declarations_are_bounded_unique_and_closed_before_render() {
invalid[field] = value;
assert!(prepare(&invalid).is_err(), "field {field}");
}
}
#[test]
fn declarations_are_bounded_unique_and_closed_before_render() {
let valid = prepare(&request(vec![function("read")])).unwrap();
assert_eq!(valid.max_output_tokens, 64);
assert!(valid.prompt.contains("read"));
let grammar = json!({"type":"grammar","syntax":"lark","definition":"start: WORD"});
for tools in [
vec![function("read"), function("read")],
vec![json!({"type":"web_search"})],
vec![json!({"type":"custom","name":"run","format":grammar})],
vec![
json!({"type":"function","name":"read","parameters":{"type":"object"},"surprise":true}),
],
(0..129).map(|i| function(&format!("read_{i}"))).collect(),
] {
assert!(prepare(&request(tools)).is_err());
}
assert_invalid_top_level_fields_refused();
let mut sampled = request(vec![function("read")]);
sampled["temperature"] = json!(0.4);
assert!(
@@ -89,7 +91,9 @@ fn choice_requires_declared_identity_and_controls_call_presence() {
#[test]
fn allowed_subset_and_parallel_false_are_enforced_after_whole_parse() {
let mut req = request(vec![function("read"), function("write")]);
req["tool_choice"] = json!({"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"read"}]});
req["tool_choice"] = json!({
"type": "allowed_tools", "mode": "required", "tools": [{"type": "function", "name": "read"}],
});
let plan = prepare(&req).unwrap();
assert!(
plan.policy
@@ -112,12 +116,7 @@ fn allowed_subset_and_parallel_false_are_enforced_after_whole_parse() {
assert!(plan.policy.parse_output(&format!("{one}\n{one}")).is_err());
}
#[test]
fn schema_required_additional_and_nullable_values_are_independent() {
let tool = json!({"type":"function","name":"read","parameters":{
"type":"object","properties":{"path":{"type":["string","null"]}},
"required":["path"],"additionalProperties":false}});
let plan = prepare(&request(vec![tool])).unwrap();
fn assert_nullable_path_values(plan: &strata_desktop_core::runtime_tools::ToolPlan) {
for (raw, expected) in [("null", Value::Null), ("123", json!("123"))] {
let parsed = plan
.policy
@@ -134,14 +133,13 @@ fn schema_required_additional_and_nullable_values_are_independent() {
assert!(item.get("call_id").is_none());
assert!(item.get("status").is_none());
}
assert!(plan.policy.parse_output(&call("read", &[])).is_err());
assert!(
plan.policy
.parse_output(&call("read", &[("path", "a"), ("extra", "1")]))
.is_err()
);
let typed = prepare(&request(vec![json!({"type":"function","name":"count","parameters":{
"type":"object","properties":{"n":{"type":"integer","minimum":1}},"required":["n"],"additionalProperties":false}})])).unwrap();
}
fn assert_integer_minimum_is_enforced() {
let count = json!({"type":"function","name":"count","parameters":{
"type":"object","properties":{"n":{"type":"integer","minimum":1}},
"required":["n"],"additionalProperties":false}});
let typed = prepare(&request(vec![count])).unwrap();
for bad in ["0", "1.5", "null", "oops"] {
assert!(
typed
@@ -158,6 +156,41 @@ fn schema_required_additional_and_nullable_values_are_independent() {
);
}
#[test]
fn schema_required_additional_and_nullable_values_are_independent() {
let tool = json!({"type":"function","name":"read","parameters":{
"type":"object","properties":{"path":{"type":["string","null"]}},
"required":["path"],"additionalProperties":false}});
let plan = prepare(&request(vec![tool])).unwrap();
assert_nullable_path_values(&plan);
assert!(plan.policy.parse_output(&call("read", &[])).is_err());
assert!(
plan.policy
.parse_output(&call("read", &[("path", "a"), ("extra", "1")]))
.is_err()
);
assert_integer_minimum_is_enforced();
}
fn assert_reference_refused(key: &str, reference: &str) {
let mut schema = json!({"type":"object","properties":{"deep":{"allOf":[{}]}}});
schema["properties"]["deep"]["allOf"][0][key] = json!(reference);
let tool = json!({"type":"function","name":"read","parameters":schema});
assert!(prepare(&request(vec![tool])).is_err(), "{key} {reference}");
}
fn assert_external_reference_forms_refuse() {
for key in ["$ref", "$dynamicRef", "$recursiveRef"] {
for reference in [
"https://example.invalid/schema",
"file:///etc/private",
"../schema.json",
] {
assert_reference_refused(key, reference);
}
}
}
#[test]
fn schema_local_refs_work_and_all_external_reference_forms_refuse() {
let schema = json!({"type":"object","$defs":{"path":{"type":"string"}},
@@ -171,23 +204,7 @@ fn schema_local_refs_work_and_all_external_reference_forms_refuse() {
.parse_output(&call("read", &[("path", "fixture")]))
.is_ok()
);
for key in ["$ref", "$dynamicRef", "$recursiveRef"] {
for reference in [
"https://example.invalid/schema",
"file:///etc/private",
"../schema.json",
] {
let mut schema = json!({"type":"object","properties":{"deep":{"allOf":[{}]}}});
schema["properties"]["deep"]["allOf"][0][key] = json!(reference);
assert!(
prepare(&request(vec![
json!({"type":"function","name":"read","parameters":schema})
]))
.is_err(),
"{key} {reference}"
);
}
}
assert_external_reference_forms_refuse();
let bad = request(vec![
json!({"type":"function","name":"read","parameters":{"type":"bogus"}}),
]);
+106 -64
View File
@@ -36,31 +36,18 @@ fn function_item() -> ValidatedSegment {
)
}
#[test]
fn publisher_indices_sequence_ids_and_deltas_have_one_terminal() {
let mut publisher = ToolResponse::new("resp_fixed".into(), "native_fixture".into());
let opening = publisher.beginning();
assert_eq!(opening.len(), 2);
for event in events(&opening) {
assert_eq!(event["response"]["output"], json!([]));
}
assert!(publisher.beginning().is_empty());
let long_text = format!("{}🦩", "x".repeat(8191));
let segments = vec![
fn mixed_segments(long_text: &str) -> Vec<ValidatedSegment> {
vec![
ValidatedSegment::Text(String::new()),
ValidatedSegment::Text(long_text.clone()),
ValidatedSegment::Text(long_text.to_string()),
function_item(),
ValidatedSegment::Call(
json!({"type":"custom_tool_call","name":"run","namespace":"ops","input":"MOVE 12"}),
),
];
let (completion, response) = publisher.complete(segments, &usage(), "stop").unwrap();
let mut all = events(&opening);
all.extend(events(&completion));
for (index, event) in all.iter().enumerate() {
assert_eq!(event["sequence_number"], index);
assert_eq!(event["response_id"], "resp_fixed");
}
]
}
fn assert_output_items_follow_their_added_events(all: &[Value], response: &Value) {
let output = response["output"].as_array().unwrap();
assert_eq!(output.len(), 3);
assert_eq!(
@@ -79,65 +66,74 @@ fn publisher_indices_sequence_ids_and_deltas_have_one_terminal() {
vec![0, 1, 2]
);
for index in 1..3 {
assert_eq!(added[index]["item"]["id"], output[index]["id"]);
assert_eq!(added[index]["item"]["call_id"], output[index]["call_id"]);
assert_eq!(output[index]["status"], "completed");
assert!(
output[index]["call_id"]
.as_str()
.unwrap()
.starts_with("call_")
);
assert_added_matches_output(added[index], &output[index]);
}
assert_ne!(output[1]["call_id"], output[2]["call_id"]);
}
fn assert_added_matches_output(added: &Value, output: &Value) {
assert_eq!(added["item"]["id"], output["id"]);
assert_eq!(added["item"]["call_id"], output["call_id"]);
assert_eq!(output["status"], "completed");
assert!(output["call_id"].as_str().unwrap().starts_with("call_"));
}
fn assert_text_deltas_rebuild(all: &[Value], long_text: &str) {
let reconstructed: String = all
.iter()
.filter(|e| e["type"] == "response.output_text.delta")
.map(|e| e["delta"].as_str().unwrap())
.collect();
assert_eq!(reconstructed, long_text);
}
/// Opens the response once: two events with an empty output, and a second `beginning` is silent.
fn open_response(publisher: &mut ToolResponse) -> Vec<axum::body::Bytes> {
let opening = publisher.beginning();
assert_eq!(opening.len(), 2);
assert!(
events(&opening)
.iter()
.all(|e| e["response"]["output"] == json!([]))
);
assert!(publisher.beginning().is_empty());
opening
}
fn assert_one_completed_terminal(all: &[Value], response: &Value) {
assert_eq!(
all.iter()
.filter(|e| e["type"] == "response.completed")
.count(),
1
);
assert_eq!(all.last().unwrap()["response"], response);
assert_eq!(all.last().unwrap()["response"], *response);
}
#[test]
fn publisher_indices_sequence_ids_and_deltas_have_one_terminal() {
let mut publisher = ToolResponse::new("resp_fixed".into(), "native_fixture".into());
let opening = open_response(&mut publisher);
let long_text = format!("{}🦩", "x".repeat(8191));
let (completion, response) = publisher
.complete(mixed_segments(&long_text), &usage(), "stop")
.unwrap();
let mut all = events(&opening);
all.extend(events(&completion));
for (index, event) in all.iter().enumerate() {
assert_eq!(event["sequence_number"], index);
assert_eq!(event["response_id"], "resp_fixed");
}
assert_output_items_follow_their_added_events(&all, &response);
assert_text_deltas_rebuild(&all, &long_text);
assert_one_completed_terminal(&all, &response);
assert!(publisher.complete(vec![], &usage(), "stop").is_err());
let (after, unchanged) = publisher.failed("invalid_tool_output");
assert!(after.is_empty());
assert_eq!(unchanged, response);
}
#[test]
fn publisher_invalid_late_item_reason_usage_and_bounds_are_atomic() {
let bad = ValidatedSegment::Call(
json!({"type":"function_call","name":"read","arguments":"{}","call_id":"injected"}),
);
let mut publisher = ToolResponse::new("resp_atomic".into(), "native_fixture".into());
assert!(
publisher
.complete(
vec![
ValidatedSegment::Text("early text".into()),
function_item(),
bad
],
&usage(),
"stop"
)
.is_err()
);
let opening = events(&publisher.beginning());
assert_eq!(opening[0]["sequence_number"], 0);
assert_eq!(opening[0]["response"]["output"], json!([]));
for reason in ["tool_calls", "unknown", ""] {
assert!(
publisher
.complete(vec![function_item()], &usage(), reason)
.is_err()
);
}
fn refuses_unusable_usage(publisher: &mut ToolResponse) {
for bad in [
Usage {
input_tokens: u64::MAX,
@@ -156,6 +152,9 @@ fn publisher_invalid_late_item_reason_usage_and_bounds_are_atomic() {
.is_err()
);
}
}
fn refuses_oversized_segment_lists(publisher: &mut ToolResponse) {
for segments in [
vec![ValidatedSegment::Text("x".repeat(8 * 1024 * 1024 + 1))],
(0..129).map(|_| function_item()).collect(),
@@ -165,6 +164,40 @@ fn publisher_invalid_late_item_reason_usage_and_bounds_are_atomic() {
] {
assert!(publisher.complete(segments, &usage(), "stop").is_err());
}
}
fn refuses_late_invalid_item(publisher: &mut ToolResponse) {
let bad = ValidatedSegment::Call(
json!({"type":"function_call","name":"read","arguments":"{}","call_id":"injected"}),
);
let segments = vec![
ValidatedSegment::Text("early text".into()),
function_item(),
bad,
];
assert!(publisher.complete(segments, &usage(), "stop").is_err());
}
fn refuses_unusable_reasons(publisher: &mut ToolResponse) {
for reason in ["tool_calls", "unknown", ""] {
assert!(
publisher
.complete(vec![function_item()], &usage(), reason)
.is_err()
);
}
}
#[test]
fn publisher_invalid_late_item_reason_usage_and_bounds_are_atomic() {
let mut publisher = ToolResponse::new("resp_atomic".into(), "native_fixture".into());
refuses_late_invalid_item(&mut publisher);
let opening = events(&publisher.beginning());
assert_eq!(opening[0]["sequence_number"], 0);
assert_eq!(opening[0]["response"]["output"], json!([]));
refuses_unusable_reasons(&mut publisher);
refuses_unusable_usage(&mut publisher);
refuses_oversized_segment_lists(&mut publisher);
let (ending, response) = publisher
.complete(vec![function_item()], &usage(), "length")
.unwrap();
@@ -196,6 +229,19 @@ fn publisher_failure_is_sanitized_and_never_creates_a_tool_item() {
assert_eq!(same, response);
}
/// The conversation that replays a published response with the result of its call.
fn replay_input(body: &Value) -> Vec<Value> {
let mut input = vec![json!({"role":"user","content":"read"})];
input.extend(body["output"].as_array().unwrap().iter().cloned());
input.push(json!({
"type": "function_call_output",
"call_id": body["output"][1]["call_id"],
"output": "REPLAY_RESULT_LITERAL",
}));
input.push(json!({"role":"user","content":"continue"}));
input
}
#[test]
fn published_standard_output_replays_exact_call_identity_with_result() {
let mut publisher = ToolResponse::new("resp_replay".into(), "native_fixture".into());
@@ -209,12 +255,8 @@ fn published_standard_output_replays_exact_call_identity_with_result() {
"stop",
)
.unwrap();
let mut input = vec![json!({"role":"user","content":"read"})];
input.extend(body["output"].as_array().unwrap().iter().cloned());
input.push(json!({"type":"function_call_output","call_id":body["output"][1]["call_id"],"output":"REPLAY_RESULT_LITERAL"}));
input.push(json!({"role":"user","content":"continue"}));
let mut req = request(vec![function("read")]);
req["input"] = json!(input);
req["input"] = json!(replay_input(&body));
let plan = prepare(&req).unwrap();
assert!(plan.prompt.contains("I will read."));
assert!(plan.prompt.contains("REPLAY_RESULT_LITERAL"));
+115 -188
View File
@@ -1,77 +1,46 @@
use axum::{Router, body::Body, routing::post};
use std::{collections::BTreeMap, time::Duration};
use strata_desktop_core::{
gateway,
node::{self, proto::*},
};
#[path = "node_contract/support.rs"]
mod support;
use std::time::Duration;
use strata_desktop_core::node::{self, proto::*};
use support::{TOKEN, fake, hello, req, serve_proxy, server, wait_until_no_active_response};
use tokio::net::TcpListener;
use tonic::Code;
const TOKEN: &str = "synthetic-test-credential-32-bytes-only";
struct Server {
address: std::net::SocketAddr,
task: tokio::task::JoinHandle<()>,
}
impl Drop for Server {
fn drop(&mut self) {
self.task.abort();
}
}
async fn server(gateway: Option<gateway::Gateway>) -> Server {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let agent = node::Agent::new(TOKEN.into(), gateway).unwrap();
let task =
tokio::spawn(async move { agent.serve(listener, std::future::pending()).await.unwrap() });
Server { address, task }
}
fn req<T>(message: T) -> tonic::Request<T> {
node::authorized(message, TOKEN).unwrap()
}
async fn fake(body: &'static str, delay: bool) -> (Server, gateway::Gateway) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let router=Router::new().route("/v1/responses",post(move ||async move {
let stream=async_stream::stream! {
if delay {tokio::time::sleep(Duration::from_millis(150)).await;}
for bytes in body.as_bytes().chunks(3) { yield Ok::<_,std::io::Error>(bytes.to_vec()); }
};
axum::response::Response::builder().header("content-type","text/event-stream").body(Body::from_stream(stream)).unwrap()
}));
let task = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
let g = gateway::Gateway::with_token(
gateway::Config {
schema_version: 1,
listen: "127.0.0.1:0".parse().unwrap(),
token_env: "UNUSED".into(),
queue_limit: 4,
queue_timeout_ms: 1000,
request_timeout_ms: 3000,
groups: vec![gateway::Group {
id: "local".into(),
slots: 1,
available_bytes: 100,
}],
deployments: vec![gateway::Deployment {
id: "test".into(),
model: "test".into(),
endpoint: format!("http://{address}"),
token_env: None,
group: "local".into(),
slots: 1,
request_bytes: 1,
capabilities: vec!["responses".into(), "tools".into()],
}],
aliases: BTreeMap::new(),
},
TOKEN.into(),
)
.unwrap();
(Server { address, task }, g)
}
type Client = node_client::NodeClient<tonic::transport::Channel>;
#[tokio::test]
async fn auth_version_capabilities_bounds_and_loopback() {
let server = server(None).await;
let mut client = node::connect(server.address).await.unwrap();
handshake_checks(&mut client).await;
unauthenticated_calls_are_refused(&mut client).await;
assert_eq!(
client
.plan(req(JsonDocument {
json: vec![b' '; 1024 * 1024 + 1]
}))
.await
.unwrap_err()
.code(),
Code::ResourceExhausted
);
assert!(
node::connect("192.0.2.1:1234".parse().unwrap())
.await
.is_err()
);
let listener = TcpListener::bind("0.0.0.0:0").await.unwrap();
assert!(
node::Agent::new(TOKEN.into(), None)
.unwrap()
.serve(listener, async {})
.await
.is_err()
);
}
async fn handshake_checks(client: &mut Client) {
assert_eq!(
client
.handshake(Hello {
@@ -92,19 +61,16 @@ async fn auth_version_capabilities_bounds_and_loopback() {
.code(),
Code::FailedPrecondition
);
let snapshot = client
.handshake(req(Hello {
protocol_version: 1,
}))
.await
.unwrap()
.into_inner();
let snapshot = client.handshake(hello()).await.unwrap().into_inner();
assert!(
!snapshot
.capabilities
.iter()
.any(|s| s.contains("responses"))
);
}
async fn unauthenticated_calls_are_refused(client: &mut Client) {
assert_eq!(
client.hardware(Empty {}).await.unwrap_err().code(),
Code::Unauthenticated
@@ -133,34 +99,9 @@ async fn auth_version_capabilities_bounds_and_loopback() {
client.watch(Cursor::default()).await.unwrap_err().code(),
Code::Unauthenticated
);
assert_eq!(
client
.plan(req(JsonDocument {
json: vec![b' '; 1024 * 1024 + 1]
}))
.await
.unwrap_err()
.code(),
Code::ResourceExhausted
);
assert!(
node::connect("192.0.2.1:1234".parse().unwrap())
.await
.is_err()
);
let listener = TcpListener::bind("0.0.0.0:0").await.unwrap();
assert!(
node::Agent::new(TOKEN.into(), None)
.unwrap()
.serve(listener, async {})
.await
.is_err()
);
}
#[tokio::test]
async fn watch_reconnect_limits_and_new_epoch_snapshot() {
let a = server(None).await;
let mut client = node::connect(a.address).await.unwrap();
async fn fill_watch_slots(client: &mut Client) -> Vec<tonic::Streaming<Snapshot>> {
let mut subscriptions = vec![];
for _ in 0..16 {
let mut stream = client
@@ -177,6 +118,14 @@ async fn watch_reconnect_limits_and_new_epoch_snapshot() {
assert_eq!(state.sequence, 1);
subscriptions.push(stream);
}
subscriptions
}
#[tokio::test]
async fn watch_reconnect_limits_and_new_epoch_snapshot() {
let a = server(None).await;
let mut client = node::connect(a.address).await.unwrap();
let subscriptions = fill_watch_slots(&mut client).await;
assert_eq!(
client
.watch(req(Cursor::default()))
@@ -186,9 +135,7 @@ async fn watch_reconnect_limits_and_new_epoch_snapshot() {
Code::ResourceExhausted
);
let epoch = client
.handshake(req(Hello {
protocol_version: 1,
}))
.handshake(hello())
.await
.unwrap()
.into_inner()
@@ -196,49 +143,29 @@ async fn watch_reconnect_limits_and_new_epoch_snapshot() {
drop(subscriptions);
let b = server(None).await;
let mut other = node::connect(b.address).await.unwrap();
let mut stream = other
.watch(req(Cursor {
agent_epoch: epoch.clone(),
sequence: 1,
}))
.await
.unwrap()
.into_inner();
let mut stream = watch_from(&mut other, &epoch, 1).await;
assert_ne!(stream.message().await.unwrap().unwrap().agent_epoch, epoch);
}
const SSE: &str = "data: {\"type\":\"response.function_call_arguments.delta\",\"delta\":\"{\\\"x\\\":1}\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_test\"}}\n\n";
#[tokio::test]
async fn responses_preserve_bytes_terminal_and_control_during_generation() {
let (_fake, g) = fake(SSE, true).await;
let server = server(Some(g)).await;
let mut client = node::connect(server.address).await.unwrap();
let mut watch = client
.watch(req(Cursor::default()))
.await
.unwrap()
.into_inner();
let first = watch.message().await.unwrap().unwrap();
let mut stream = client
.respond(req(ResponseRequest {
json: br#"{"model":"test","stream":true,"input":"synthetic"}"#.to_vec(),
}))
.await
.unwrap()
.into_inner();
let active = watch.message().await.unwrap().unwrap();
assert_eq!(active.active_responses, 1);
assert!(active.sequence > first.sequence);
let snapshot = tokio::time::timeout(
Duration::from_secs(1),
client.handshake(req(Hello {
protocol_version: 1,
})),
)
.await
.unwrap()
.unwrap()
.into_inner();
assert_eq!(snapshot.active_responses, 1);
async fn watch_from(
client: &mut Client,
agent_epoch: &str,
sequence: u64,
) -> tonic::Streaming<Snapshot> {
let cursor = Cursor {
agent_epoch: agent_epoch.into(),
sequence,
};
client.watch(req(cursor)).await.unwrap().into_inner()
}
const SSE: &str = concat!(
"data: {\"type\":\"response.function_call_arguments.delta\",\"delta\":\"{\\\"x\\\":1}\"}\n\n",
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_test\"}}\n\n"
);
/// Reads every frame of a response: one `Headers` (200), then data, then one `End`.
async fn collect_ordered_frames(stream: &mut tonic::Streaming<ResponseFrame>) -> Vec<u8> {
let mut bytes = vec![];
let mut end = false;
let mut headers = false;
@@ -260,17 +187,46 @@ async fn responses_preserve_bytes_terminal_and_control_during_generation() {
}
}
assert!(end);
assert_eq!(bytes, SSE.as_bytes());
let complete = watch.message().await.unwrap().unwrap();
assert_eq!(complete.active_responses, 0);
let reconnect = client
.watch(req(Cursor {
agent_epoch: complete.agent_epoch.clone(),
sequence: 1,
}))
bytes
}
async fn assert_one_active_response_in_a_handshake(client: &mut Client) {
let snapshot = tokio::time::timeout(Duration::from_secs(1), client.handshake(hello()))
.await
.unwrap()
.into_inner()
.unwrap()
.into_inner();
assert_eq!(snapshot.active_responses, 1);
}
async fn start_synthetic_response(client: &mut Client) -> tonic::Streaming<ResponseFrame> {
let request = ResponseRequest {
json: br#"{"model":"test","stream":true,"input":"synthetic"}"#.to_vec(),
};
client.respond(req(request)).await.unwrap().into_inner()
}
#[tokio::test]
async fn responses_preserve_bytes_terminal_and_control_during_generation() {
let (_fake, g) = fake(SSE, true).await;
let server = server(Some(g)).await;
let mut client = node::connect(server.address).await.unwrap();
let mut watch = client
.watch(req(Cursor::default()))
.await
.unwrap()
.into_inner();
let first = watch.message().await.unwrap().unwrap();
let mut stream = start_synthetic_response(&mut client).await;
let active = watch.message().await.unwrap().unwrap();
assert_eq!(active.active_responses, 1);
assert!(active.sequence > first.sequence);
assert_one_active_response_in_a_handshake(&mut client).await;
assert_eq!(collect_ordered_frames(&mut stream).await, SSE.as_bytes());
let complete = watch.message().await.unwrap().unwrap();
assert_eq!(complete.active_responses, 0);
let reconnect = watch_from(&mut client, &complete.agent_epoch, 1)
.await
.message()
.await
.unwrap()
@@ -278,6 +234,7 @@ async fn responses_preserve_bytes_terminal_and_control_during_generation() {
assert_eq!(reconnect.sequence, complete.sequence);
assert!(reconnect.full_snapshot);
}
#[tokio::test]
async fn interrupted_upstream_is_error_not_end_and_quarantines() {
let (_fake, g) = fake("data: {\"type\":\"response.created\"}\n\n", false).await;
@@ -351,38 +308,8 @@ async fn disconnect_releases_transport_count_but_does_not_reuse_unconfirmed_work
Some(response_frame::Payload::Headers(_))
));
drop(stream);
tokio::time::timeout(Duration::from_secs(2), async {
loop {
if client
.handshake(req(Hello {
protocol_version: 1,
}))
.await
.unwrap()
.into_inner()
.active_responses
== 0
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
wait_until_no_active_response(&mut client).await;
let mut second = client.respond(input()).await.unwrap().into_inner();
assert!(
matches!(second.message().await.unwrap().unwrap().payload,Some(response_frame::Payload::Headers(h)) if h.status==504)
);
}
/// An HTTP proxy in front of `node`, speaking gRPC to it with the test credential.
async fn serve_proxy(node: &Server) -> Server {
let proxy = strata_desktop_core::node_proxy::Proxy::connect(node.address, TOKEN.into())
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let task = tokio::spawn(async move { axum::serve(listener, proxy.router()).await.unwrap() });
Server { address, task }
let header = second.message().await.unwrap().unwrap().payload;
assert!(matches!(header, Some(response_frame::Payload::Headers(h)) if h.status == 504));
}
+131
View File
@@ -0,0 +1,131 @@
//! Servers, the fake worker and the HTTP proxy of the node contract tests.
use axum::{Router, body::Body, routing::post};
use std::{collections::BTreeMap, time::Duration};
use strata_desktop_core::{
gateway,
node::{self, proto::*},
};
use tokio::net::TcpListener;
pub const TOKEN: &str = "synthetic-test-credential-32-bytes-only";
pub struct Server {
pub address: std::net::SocketAddr,
task: tokio::task::JoinHandle<()>,
}
impl Drop for Server {
fn drop(&mut self) {
self.task.abort();
}
}
pub async fn server(gateway: Option<gateway::Gateway>) -> Server {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let agent = node::Agent::new(TOKEN.into(), gateway).unwrap();
let task =
tokio::spawn(async move { agent.serve(listener, std::future::pending()).await.unwrap() });
Server { address, task }
}
pub fn req<T>(message: T) -> tonic::Request<T> {
node::authorized(message, TOKEN).unwrap()
}
pub fn hello() -> tonic::Request<Hello> {
req(Hello {
protocol_version: 1,
})
}
fn sse_router(body: &'static str, delay: bool) -> Router {
Router::new().route(
"/v1/responses",
post(move || async move {
let stream = async_stream::stream! {
if delay {
tokio::time::sleep(Duration::from_millis(150)).await;
}
for bytes in body.as_bytes().chunks(3) {
yield Ok::<_, std::io::Error>(bytes.to_vec());
}
};
axum::response::Response::builder()
.header("content-type", "text/event-stream")
.body(Body::from_stream(stream))
.unwrap()
}),
)
}
fn gateway_config(address: std::net::SocketAddr) -> gateway::Config {
gateway::Config {
schema_version: 1,
listen: "127.0.0.1:0".parse().unwrap(),
token_env: "UNUSED".into(),
queue_limit: 4,
queue_timeout_ms: 1000,
request_timeout_ms: 3000,
groups: vec![gateway::Group {
id: "local".into(),
slots: 1,
available_bytes: 100,
}],
deployments: vec![gateway::Deployment {
id: "test".into(),
model: "test".into(),
endpoint: format!("http://{address}"),
token_env: None,
group: "local".into(),
slots: 1,
request_bytes: 1,
capabilities: vec!["responses".into(), "tools".into()],
}],
aliases: BTreeMap::new(),
}
}
pub async fn fake(body: &'static str, delay: bool) -> (Server, gateway::Gateway) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let router = sse_router(body, delay);
let task = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
let g = gateway::Gateway::with_token(gateway_config(address), TOKEN.into()).unwrap();
(Server { address, task }, g)
}
/// An HTTP proxy in front of `node`, speaking gRPC to it with the test credential.
pub async fn serve_proxy(node: &Server) -> Server {
let proxy = strata_desktop_core::node_proxy::Proxy::connect(node.address, TOKEN.into())
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let task = tokio::spawn(async move { axum::serve(listener, proxy.router()).await.unwrap() });
Server { address, task }
}
/// Polls the handshake until no response is active any more.
pub async fn wait_until_no_active_response(
client: &mut node_client::NodeClient<tonic::transport::Channel>,
) {
tokio::time::timeout(Duration::from_secs(2), async {
loop {
if client
.handshake(hello())
.await
.unwrap()
.into_inner()
.active_responses
== 0
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
@@ -39,6 +39,18 @@ async fn uncertain_dispatch_never_replays_or_advertises_ready() {
assert_eq!(f.get("/v1/models", true).await.1["data"], json!([]));
}
fn assert_single_failed_terminal(events: &[serde_json::Value]) {
assert_eq!(
events
.iter()
.filter(|v| v["type"] == "response.failed")
.count(),
1
);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(!events.iter().any(|v| v["type"] == "response.completed"));
}
#[tokio::test]
async fn accepted_faults_missing_terminal_and_tool_reason_fail_without_retry() {
if credential_child(
@@ -57,16 +69,7 @@ async fn accepted_faults_missing_terminal_and_tool_reason_fail_without_retry() {
assert_eq!(response.status(), 200);
let text = response.text().await.unwrap();
assert!(!text.contains(PRIVATE_ERROR));
let events = sse(&text);
assert_eq!(
events
.iter()
.filter(|v| v["type"] == "response.failed")
.count(),
1
);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(!events.iter().any(|v| v["type"] == "response.completed"));
assert_single_failed_terminal(&sse(&text));
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 1);
if matches!(behavior, Behavior::MissingTerminal) {
assert_eq!(f.get("/v1/models", true).await.1["data"], json!([]));
@@ -74,6 +77,30 @@ async fn accepted_faults_missing_terminal_and_tool_reason_fail_without_retry() {
}
}
async fn wait_until_not_advertised(f: &Fixture, end: tokio::time::Instant) {
loop {
let catalog = f.get("/v1/models", true).await.1;
if catalog["data"] == json!([]) {
break;
}
assert!(
tokio::time::Instant::now() < end,
"uncertain acceptance stayed advertised ready"
);
tokio::time::sleep(Duration::from_millis(2)).await;
}
}
async fn wait_until_cancelled(f: &Fixture, end: tokio::time::Instant) {
while !f.facts[0].cancelled.load(Ordering::SeqCst) {
assert!(
tokio::time::Instant::now() < end,
"lost acknowledgement did not schedule cancellation"
);
tokio::time::sleep(Duration::from_millis(2)).await;
}
}
#[tokio::test]
async fn lost_acknowledgement_withdraws_readiness_without_replay() {
if credential_child("dispatch_faults::lost_acknowledgement_withdraws_readiness_without_replay")
@@ -86,24 +113,8 @@ async fn lost_acknowledgement_withdraws_readiness_without_replay() {
assert_eq!(status, 502);
assert_eq!(value["error"]["type"], "runtime_dispatch_failed");
let end = tokio::time::Instant::now() + Duration::from_secs(2);
loop {
let catalog = f.get("/v1/models", true).await.1;
if catalog["data"] == json!([]) {
break;
}
assert!(
tokio::time::Instant::now() < end,
"uncertain acceptance stayed advertised ready"
);
tokio::time::sleep(Duration::from_millis(2)).await;
}
while !f.facts[0].cancelled.load(Ordering::SeqCst) {
assert!(
tokio::time::Instant::now() < end,
"lost acknowledgement did not schedule cancellation"
);
tokio::time::sleep(Duration::from_millis(2)).await;
}
wait_until_not_advertised(&f, end).await;
wait_until_cancelled(&f, end).await;
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 1);
let (_, states) = f.get("/runtime/status", true).await;
assert_eq!(states["runtimes"][0]["model_ready"], false);
@@ -4,7 +4,7 @@ use leleka_backend_api as api;
use serde_json::{Value, json};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::time::Duration;
use strata_desktop_core::runtime_gateway::{Config, Member, Registry};
use strata_desktop_core::runtime_rpc::RuntimeServer;
use tokio::task::JoinHandle;
@@ -140,12 +140,7 @@ impl api::Backend for LiteralBackend {
.lock()
.unwrap()
.push(request.request_id);
if matches!(self.behavior, Behavior::CapacityTwice) && attempt < 2 {
return Err(failure(api::ErrorCode::ResourceExhausted));
}
if matches!(self.behavior, Behavior::Uncertain) {
return Err(failure(api::ErrorCode::BackendUnavailable));
}
self.refuse_before_acceptance(attempt)?;
if matches!(self.behavior, Behavior::DelayedAck) {
// Exceed the daemon's two-second dispatch budget. Its HTTP/2
// observation disappears before a backend acceptance reply exists.
@@ -154,40 +149,23 @@ impl api::Backend for LiteralBackend {
let (sink, stream) = api::GenerationSink::bounded_channel(4).unwrap();
let facts = self.facts.clone();
let behavior = self.behavior;
std::thread::spawn(move || {
if matches!(behavior, Behavior::MissingTerminal) {
return;
}
let _ = sink.emit(api::GenerationEvent::TextDelta {
text: "Літерал".into(),
});
if matches!(behavior, Behavior::WaitForCancel) {
let end = Instant::now() + Duration::from_secs(5);
while !facts.cancelled.load(Ordering::SeqCst) && Instant::now() < end {
std::thread::sleep(Duration::from_millis(2));
}
let _ = sink.cancel();
} else if matches!(behavior, Behavior::AcceptedFailure) {
let _ = sink.fail(api::ErrorCode::BackendUnavailable, PRIVATE_ERROR, true);
} else {
let usage = api::Usage {
input_tokens: 7,
output_tokens: 1,
reused_input_tokens: 0,
};
let _ = sink.emit(api::GenerationEvent::Usage(usage.clone()));
let reason = if matches!(behavior, Behavior::ToolReason) {
api::FinishReason::ToolCalls
} else {
api::FinishReason::Stop
};
let _ = sink.complete(reason, usage);
}
});
std::thread::spawn(move || crate::scripted::script_generation(sink, facts, behavior));
Ok(stream)
}
}
impl LiteralBackend {
fn refuse_before_acceptance(&self, attempt: usize) -> Result<(), api::BackendError> {
if matches!(self.behavior, Behavior::CapacityTwice) && attempt < 2 {
return Err(failure(api::ErrorCode::ResourceExhausted));
}
if matches!(self.behavior, Behavior::Uncertain) {
return Err(failure(api::ErrorCode::BackendUnavailable));
}
Ok(())
}
}
pub(super) struct Fixture {
pub(super) base: String,
pub(super) http: reqwest::Client,
@@ -215,32 +193,7 @@ impl Fixture {
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let listen = listener.local_addr().unwrap();
let mut facts = Vec::new();
let mut tasks = Vec::new();
let mut runtimes = Vec::new();
for (index, behavior) in behaviors.iter().copied().enumerate() {
let observed = Arc::new(Facts::default());
let server = RuntimeServer::new(
Box::new(LiteralBackend {
facts: observed.clone(),
behavior,
}),
TOKEN.into(),
)
.unwrap();
let rpc = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = rpc.local_addr().unwrap();
tasks.push(tokio::spawn(async move {
server.serve(rpc, std::future::pending()).await.unwrap();
}));
runtimes.push(Member {
id: format!("native{index}"),
address,
token_env: ENV.into(),
artifact_digest: descriptor().artifact_digest,
});
facts.push(observed);
}
let (runtimes, facts, mut tasks) = spawn_runtimes(behaviors).await;
let registry = Registry::new(Config {
schema_version: 1,
listen,
@@ -250,15 +203,10 @@ impl Fixture {
experimental_native_tools: false,
})
.unwrap();
tasks.push(tokio::spawn(async move {
axum::serve(listener, registry.router()).await.unwrap();
}));
tasks.push(serve_registry(listener, registry));
Self {
base: format!("http://{listen}"),
http: reqwest::Client::builder()
.timeout(Duration::from_secs(4))
.build()
.unwrap(),
http: http_client(4),
facts,
tasks,
}
@@ -297,7 +245,11 @@ impl Fixture {
.into()
}
pub(super) async fn outcome(&self, command: &Value) -> Value {
let query = json!({"model":command["model"],"operation_id":command["operation_id"],"epoch":command["epoch"]});
let query = json!({
"model": command["model"],
"operation_id": command["operation_id"],
"epoch": command["epoch"],
});
let end = tokio::time::Instant::now() + Duration::from_secs(2);
loop {
let (status, value) = self.post("/runtime/operation", query.clone()).await;
@@ -313,17 +265,83 @@ impl Fixture {
}
}
pub(super) async fn native(&self, model: &str) -> Value {
let command = json!({"model":model,"operation_id":uuid::Uuid::new_v4().to_string(),"epoch":self.epoch(model).await,"mode":"native"});
let command = json!({
"model": model,
"operation_id": uuid::Uuid::new_v4().to_string(),
"epoch": self.epoch(model).await,
"mode": "native",
});
let (status, _) = self.post("/runtime/load", command.clone()).await;
assert_eq!(status, 200);
assert_eq!(self.outcome(&command).await["state"], 2);
command
}
pub(super) async fn response(&self, stream: bool) -> reqwest::Response {
self.http.post(format!("{}/v1/responses", self.base)).bearer_auth(TOKEN).header("content-type", "application/json").body(json!({"model":"native0","input":"synthetic question","max_output_tokens":1,"stream":stream}).to_string()).send().await.unwrap()
let body = json!({
"model": "native0", "input": "synthetic question", "max_output_tokens": 1, "stream": stream,
});
self.http
.post(format!("{}/v1/responses", self.base))
.bearer_auth(TOKEN)
.header("content-type", "application/json")
.body(body.to_string())
.send()
.await
.unwrap()
}
}
async fn spawn_runtimes(
behaviors: &[Behavior],
) -> (Vec<Member>, Vec<Arc<Facts>>, Vec<JoinHandle<()>>) {
let (mut runtimes, mut facts, mut tasks) = (Vec::new(), Vec::new(), Vec::new());
for (index, behavior) in behaviors.iter().copied().enumerate() {
let (member, observed, task) = spawn_runtime(index, behavior).await;
tasks.push(task);
runtimes.push(member);
facts.push(observed);
}
(runtimes, facts, tasks)
}
/// One runtime server over a literal backend of `behavior`: its gateway member, observed facts and task.
async fn spawn_runtime(index: usize, behavior: Behavior) -> (Member, Arc<Facts>, JoinHandle<()>) {
let observed = Arc::new(Facts::default());
let server = RuntimeServer::new(
Box::new(LiteralBackend {
facts: observed.clone(),
behavior,
}),
TOKEN.into(),
)
.unwrap();
let rpc = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = rpc.local_addr().unwrap();
let task = tokio::spawn(async move {
server.serve(rpc, std::future::pending()).await.unwrap();
});
let member = Member {
id: format!("native{index}"),
address,
token_env: ENV.into(),
artifact_digest: descriptor().artifact_digest,
};
(member, observed, task)
}
fn serve_registry(listener: tokio::net::TcpListener, registry: Registry) -> JoinHandle<()> {
tokio::spawn(async move {
axum::serve(listener, registry.router()).await.unwrap();
})
}
fn http_client(seconds: u64) -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(seconds))
.build()
.unwrap()
}
pub(super) async fn decode(response: reqwest::Response) -> (u16, Value) {
let code = response.status().as_u16();
let text = response.text().await.unwrap();
@@ -41,7 +41,12 @@ async fn completed_unload_duplicate_returns_retained_outcome_without_reexecution
}
let f = Fixture::new(&[Behavior::Complete]).await;
let loaded = f.native("native0").await;
let command = json!({"model":"native0","operation_id":uuid::Uuid::new_v4().to_string(),"epoch":loaded["epoch"],"handle":"literal-native-handle"});
let command = json!({
"model": "native0",
"operation_id": uuid::Uuid::new_v4().to_string(),
"epoch": loaded["epoch"],
"handle": "literal-native-handle",
});
assert_eq!(f.post("/runtime/unload", command.clone()).await.0, 200);
assert_eq!(f.outcome(&command).await["state"], 2);
assert_eq!(f.get("/v1/models", true).await.1["data"], json!([]));
@@ -6,4 +6,5 @@
mod dispatch_faults;
mod harness;
mod lifecycle;
mod scripted;
mod text_flow;
@@ -0,0 +1,43 @@
//! The scripted generation thread of the literal backend of the runtime gateway tests.
use crate::harness::{Behavior, Facts, PRIVATE_ERROR};
use leleka_backend_api as api;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
/// What the generation thread of the literal backend emits for one scripted behavior.
pub(super) fn script_generation(sink: api::GenerationSink, facts: Arc<Facts>, behavior: Behavior) {
if matches!(behavior, Behavior::MissingTerminal) {
return;
}
let _ = sink.emit(api::GenerationEvent::TextDelta {
text: "Літерал".into(),
});
if matches!(behavior, Behavior::WaitForCancel) {
let end = Instant::now() + Duration::from_secs(5);
while !facts.cancelled.load(Ordering::SeqCst) && Instant::now() < end {
std::thread::sleep(Duration::from_millis(2));
}
let _ = sink.cancel();
} else if matches!(behavior, Behavior::AcceptedFailure) {
let _ = sink.fail(api::ErrorCode::BackendUnavailable, PRIVATE_ERROR, true);
} else {
complete_with_usage(&sink, behavior);
}
}
fn complete_with_usage(sink: &api::GenerationSink, behavior: Behavior) {
let usage = api::Usage {
input_tokens: 7,
output_tokens: 1,
reused_input_tokens: 0,
};
let _ = sink.emit(api::GenerationEvent::Usage(usage.clone()));
let reason = if matches!(behavior, Behavior::ToolReason) {
api::FinishReason::ToolCalls
} else {
api::FinishReason::Stop
};
let _ = sink.complete(reason, usage);
}
@@ -5,6 +5,29 @@ use leleka_backend_api as api;
use serde_json::json;
use std::sync::atomic::Ordering;
const PLE_PROFILE: &str = "qwen38-flash-next-ple-l2-cache64-v1";
fn ple_load_command(epoch: &str) -> serde_json::Value {
json!({
"model": "native0",
"operation_id": uuid::Uuid::new_v4().to_string(),
"epoch": epoch,
"mode": "kar-ple",
"profile_id": PLE_PROFILE,
})
}
fn assert_native_then_ple_loads(configs: &[api::RuntimeConfig]) {
assert_eq!(configs.len(), 2);
assert_eq!(configs[0].inference_mode, api::InferenceMode::Native);
assert!(!configs[0].allow_experimental);
let mode = &configs[1].inference_mode;
assert!(
matches!(mode, api::InferenceMode::ExperimentalKarPle { profile_id } if profile_id == PLE_PROFILE)
);
assert!(configs[1].allow_experimental);
}
#[tokio::test]
async fn catalog_auth_explicit_load_refusal_preserves_other_members() {
if credential_child("text_flow::catalog_auth_explicit_load_refusal_preserves_other_members") {
@@ -20,17 +43,10 @@ async fn catalog_auth_explicit_load_refusal_preserves_other_members() {
assert!(f.facts[0].loads.lock().unwrap().is_empty());
f.native("native0").await;
f.native("native1").await;
let ple = json!({"model":"native0","operation_id":uuid::Uuid::new_v4().to_string(),"epoch":epoch,"mode":"kar-ple","profile_id":"qwen38-flash-next-ple-l2-cache64-v1"});
let ple = ple_load_command(&epoch);
assert_eq!(f.post("/runtime/load", ple.clone()).await.0, 200);
assert_eq!(f.outcome(&ple).await["state"], 3);
let configs = f.facts[0].loads.lock().unwrap().clone();
assert_eq!(configs.len(), 2);
assert_eq!(configs[0].inference_mode, api::InferenceMode::Native);
assert!(!configs[0].allow_experimental);
assert!(
matches!(&configs[1].inference_mode, api::InferenceMode::ExperimentalKarPle { profile_id } if profile_id == "qwen38-flash-next-ple-l2-cache64-v1")
);
assert!(configs[1].allow_experimental);
assert_native_then_ple_loads(&f.facts[0].loads.lock().unwrap().clone());
let catalog = f.get("/v1/models", true).await.1;
let ids = catalog["data"]
.as_array()
@@ -42,6 +58,18 @@ async fn catalog_auth_explicit_load_refusal_preserves_other_members() {
assert_eq!(f.facts[0].starts.load(Ordering::SeqCst), 0);
}
const TEXT_EVENT_TYPES: [&str; 9] = [
"response.created",
"response.in_progress",
"response.output_item.added",
"response.content_part.added",
"response.output_text.delta",
"response.output_text.done",
"response.content_part.done",
"response.output_item.done",
"response.completed",
];
#[tokio::test]
async fn actual_http2_text_maps_single_ordered_sse_terminal() {
if credential_child("text_flow::actual_http2_text_maps_single_ordered_sse_terminal") {
@@ -57,20 +85,7 @@ async fn actual_http2_text_maps_single_ordered_sse_terminal() {
.iter()
.map(|v| v["type"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(
types,
[
"response.created",
"response.in_progress",
"response.output_item.added",
"response.content_part.added",
"response.output_text.delta",
"response.output_text.done",
"response.content_part.done",
"response.output_item.done",
"response.completed"
]
);
assert_eq!(types, TEXT_EVENT_TYPES);
for (i, event) in events.iter().enumerate() {
assert_eq!(event["sequence_number"], i);
}
+23 -16
View File
@@ -4,19 +4,25 @@ use tokio::{
process::Command,
};
#[tokio::test]
async fn owned_tunnel_bootstrap_ends_at_parent_eof() {
let mut child = Command::new(env!("CARGO_BIN_EXE_strata-desktop"))
const BOOTSTRAP: &[u8] = concat!(
"{\"schema_version\":1,\"ssh\":{\"schema_version\":1,\"id\":\"fixture\",\"host\":\"localhost\"},",
"\"listen\":\"127.0.0.1:0\",\"remote_port\":19999,\"max_connections\":1}\n"
)
.as_bytes();
fn spawn_stdio_tunnel() -> tokio::process::Child {
Command::new(env!("CARGO_BIN_EXE_strata-desktop"))
.args(["ssh-tunnel", "--stdio-lifetime"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.unwrap();
let mut input = child.stdin.take().unwrap();
input.write_all(br#"{"schema_version":1,"ssh":{"schema_version":1,"id":"fixture","host":"localhost"},"listen":"127.0.0.1:0","remote_port":19999,"max_connections":1}
"#).await.unwrap();
.unwrap()
}
/// The endpoint descriptor the tunnel prints on its first stdout line.
async fn read_descriptor(child: &mut tokio::process::Child) -> serde_json::Value {
let mut line = String::new();
tokio::time::timeout(
Duration::from_secs(5),
@@ -25,7 +31,15 @@ async fn owned_tunnel_bootstrap_ends_at_parent_eof() {
.await
.unwrap()
.unwrap();
let descriptor: serde_json::Value = serde_json::from_str(&line).unwrap();
serde_json::from_str(&line).unwrap()
}
#[tokio::test]
async fn owned_tunnel_bootstrap_ends_at_parent_eof() {
let mut child = spawn_stdio_tunnel();
let mut input = child.stdin.take().unwrap();
input.write_all(BOOTSTRAP).await.unwrap();
let descriptor = read_descriptor(&mut child).await;
assert_eq!(descriptor["transport"], "ssh");
assert_eq!(
descriptor["readiness"],
@@ -50,14 +64,7 @@ async fn owned_tunnel_bootstrap_ends_at_parent_eof() {
#[tokio::test]
async fn incomplete_bootstrap_is_not_an_open_listener() {
let mut child = Command::new(env!("CARGO_BIN_EXE_strata-desktop"))
.args(["ssh-tunnel", "--stdio-lifetime"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.unwrap();
let mut child = spawn_stdio_tunnel();
child
.stdin
.take()