STRA-338 size-fn: desktop-core tests and examples within the function limits (fn>30 44 -> 0, wide lines 16 -> 0)
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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"}}),
|
||||
]);
|
||||
|
||||
@@ -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
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user