Files
leleka/control-plane/tests/backend_worker_http/runtime_status.rs
T

120 lines
4.6 KiB
Rust

//! Chat Completions over the same worker, and status, metrics and unload.
use crate::harness::{Stack, body, scripted_text, sse_events, tool_markup, usage};
use leleka_backend_api::FinishReason;
use leleka_backend_api::scripted::Script;
use serde_json::{Value, json};
use leleka_control_plane::worker::WorkerState;
fn chat_request(stream: bool) -> Value {
json!({"model": "fixture", "stream": stream, "messages": [{"role": "user", "content": "hi"}]})
}
async fn assert_chat_json_answer(stack: &Stack) {
stack
.engine
.push(Script::stop_with(&["hel", "lo"], usage(7, 2, 0)));
let (status, text) = stack
.post("/v1/chat/completions", &chat_request(false))
.await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
assert_eq!(response["choices"][0]["message"]["content"], "hello");
assert_eq!(response["choices"][0]["finish_reason"], "stop");
assert_eq!(response["usage"]["completion_tokens"], 2);
}
async fn assert_chat_stream_ends_with_length(stack: &Stack) {
stack.engine.push(Script::finishing(
&["cut"],
FinishReason::Length,
usage(7, 1, 0),
));
let (status, text) = stack
.post("/v1/chat/completions", &chat_request(true))
.await;
assert_eq!(status, 200, "{text}");
assert!(text.trim_end().ends_with("data: [DONE]"), "{text}");
let chunks = sse_events(&text);
let content: String = chunks
.iter()
.filter_map(|c| c["choices"][0]["delta"]["content"].as_str())
.collect();
assert_eq!(content, "cut");
assert_eq!(
chunks
.iter()
.filter_map(|c| c["choices"][0]["finish_reason"].as_str())
.collect::<Vec<_>>(),
vec!["length"]
);
}
fn lookup_tool() -> Value {
let key = json!({"type": "object", "properties": {"key": {"type": "string"}}});
json!({"type": "function", "function": {"name": "lookup", "parameters": key}})
}
/// Tool call through Chat: finish_reason tool_calls, arguments intact.
async fn assert_chat_tool_call(stack: &Stack) {
let markup = tool_markup("lookup", &json!({"key": "value"}));
scripted_text(&stack.engine, &markup, 6);
let request = json!({"model": "fixture", "messages": [{"role": "user", "content": "go"}],
"tools": [lookup_tool()]});
let (status, text) = stack.post("/v1/chat/completions", &request).await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
let choice = &response["choices"][0];
assert_eq!(choice["finish_reason"], "tool_calls");
let call = &choice["message"]["tool_calls"][0];
assert_eq!(call["function"]["name"], "lookup");
assert_eq!(
serde_json::from_str::<Value>(call["function"]["arguments"].as_str().unwrap()).unwrap(),
json!({"key": "value"})
);
}
#[tokio::test]
async fn chat_completions_stream_and_json_over_the_same_worker() {
let stack = Stack::start("bw-chat").await;
assert_chat_json_answer(&stack).await;
assert_chat_stream_ends_with_length(&stack).await;
assert_chat_tool_call(&stack).await;
// An engine death in Chat is an error object plus [DONE], never a success.
stack.engine.push(Script::dying_after(&["x"]));
let (_, text) = stack
.post("/v1/chat/completions", &chat_request(true))
.await;
assert!(text.contains("\"error\""), "{text}");
assert!(!text.contains("\"finish_reason\":\"stop\""), "{text}");
stack.finish().await;
}
#[tokio::test]
async fn status_metrics_and_unload_reflect_the_attached_runtime() {
let stack = Stack::start("bw-status").await;
let (status, text) = stack.get("/ready").await;
assert_eq!(status, 200, "{text}");
stack
.engine
.push(Script::stop_with(&["a", "b"], usage(4, 2, 1)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
let generation = &metrics["generation"];
assert_eq!(generation["started"], 1);
assert_eq!(generation["completed"], 1);
assert_eq!(generation["done_generated_tokens"], 2);
assert_eq!(generation["done_prompt_tokens"], 4);
assert_eq!(generation["last_done"]["reused_tokens"], 1);
assert_eq!(generation["last_done"]["finish"], "stop");
// The runtime's lifecycle belongs to its operator: HTTP cannot unload it.
assert_eq!(
leleka_control_plane::server_api::unload(&stack.state, None).await,
leleka_serving_policy::idle::Outcome::Unsupported
);
assert_eq!(stack.status.read().await.state, WorkerState::Ready);
assert!(stack.engine.is_ready());
stack.finish().await;
}