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

229 lines
8.3 KiB
Rust

//! Engine failure, loss, disconnects, deadlines and protocol violations end in exactly one terminal event.
use crate::harness::{Stack, assert_stream_invariants, body, sse_events, text_of, usage};
use leleka_backend_api::ErrorCode;
use leleka_backend_api::scripted::{Script, Step};
use serde_json::{Value, json};
use std::time::Duration;
use leleka_control_plane::worker::WorkerState;
/// A failure after one piece ends the stream with `response.failed` carrying the engine's message.
async fn assert_streamed_failure_ends_with_response_failed(stack: &Stack) {
stack.engine.push(Script::failing_after(
&["par"],
ErrorCode::ResourceExhausted,
"scripted engine failure",
));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
let last = events.last().unwrap();
assert_eq!(last["type"], "response.failed");
assert!(
last["response"]["error"]["message"]
.as_str()
.unwrap()
.contains("scripted engine failure")
);
}
#[tokio::test]
async fn an_engine_failure_terminal_ends_the_stream_with_response_failed() {
let stack = Stack::start("bw-fail").await;
assert_streamed_failure_ends_with_response_failed(&stack).await;
stack.engine.push(Script::failing_after(
&[],
ErrorCode::Internal,
"scripted engine failure",
));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 502, "{text}");
assert_eq!(
serde_json::from_str::<Value>(&text).unwrap()["error"]["code"],
"generation_failed"
);
// The engine is healthy: the worker stays ready.
assert_eq!(stack.status.read().await.state, WorkerState::Ready);
stack.finish().await;
}
#[tokio::test]
async fn an_engine_that_dies_mid_stream_still_gets_a_terminal_event_and_the_worker_recovers() {
let stack = Stack::start("bw-die").await;
stack.engine.push(Script::dying_after(&["half"]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
// The engine process is gone: not ready, and a request is refused, not hung.
stack.engine.restart_engine();
stack.wait_state(WorkerState::Restarting).await;
let (status, _) = stack.get("/ready").await;
assert_eq!(status, 503);
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 503, "{text}");
// The runtime comes back with the model loaded again: the worker attaches by itself.
stack.engine.reload_engine();
stack.wait_state(WorkerState::Ready).await;
stack
.engine
.push(Script::stop_with(&["back"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
assert_eq!(text_of(&serde_json::from_str(&text).unwrap()), "back");
stack.finish().await;
}
#[tokio::test]
async fn a_dead_engine_fails_a_buffered_request_instead_of_hanging_it() {
let stack = Stack::start("bw-die-buffered").await;
stack.engine.push(Script::dying_after(&["half"]));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 502, "{text}");
assert_eq!(
serde_json::from_str::<Value>(&text).unwrap()["error"]["type"],
"server_error"
);
stack.finish().await;
}
/// Read until the first text delta, then walk away.
async fn read_until_first_delta(response: &mut reqwest::Response) {
let mut seen = String::new();
while !seen.contains("response.output_text.delta") {
let chunk = tokio::time::timeout(Duration::from_secs(10), response.chunk())
.await
.unwrap()
.unwrap()
.expect("stream ended early");
seen.push_str(&String::from_utf8_lossy(&chunk));
}
}
async fn wait_until_cancelled(stack: &Stack) {
tokio::time::timeout(Duration::from_secs(10), async {
while stack.engine.is_generating() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the engine generation was cancelled");
}
#[tokio::test]
async fn a_client_disconnect_cancels_the_engine_and_frees_it_for_the_next_request() {
let stack = Stack::start("bw-disconnect").await;
stack.engine.push(Script::hanging_after(&["start"]));
let mut response = stack
.client
.post(format!("{}/v1/responses", stack.base))
.header("content-type", "application/json")
.body(body(json!({"stream": true})).to_string())
.send()
.await
.unwrap();
read_until_first_delta(&mut response).await;
drop(response);
wait_until_cancelled(&stack).await;
assert_eq!(stack.engine.cancels().len(), 1);
stack
.engine
.push(Script::stop_with(&["again"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
assert_eq!(metrics["generation"]["cancelled"], 1);
assert_eq!(metrics["generation"]["completed"], 1);
stack.finish().await;
}
#[tokio::test]
async fn the_generation_deadline_cancels_the_engine_and_fails_the_request() {
let stack = Stack::start_with("bw-deadline", |config| {
config.generation_timeout = Some(Duration::from_millis(150));
})
.await;
stack.engine.push(Script::hanging_after(&["slow"]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
let last = events.last().unwrap();
assert_eq!(last["type"], "response.failed");
assert!(
last["response"]["error"]["message"]
.as_str()
.unwrap()
.contains("execution deadline")
);
assert_eq!(stack.engine.cancels().len(), 1);
stack.finish().await;
}
#[tokio::test]
async fn an_engine_that_ignores_cancellation_is_treated_as_lost_after_the_drain_timeout() {
let stack = Stack::start_with("bw-drain", |config| {
config.generation_timeout = Some(Duration::from_millis(100));
config.cancel_drain_timeout = Duration::from_millis(200);
})
.await;
// A wedged engine: it produced a delta and then ignores everything, including cancel.
stack.engine.push(Script::new(vec![
Step::Text("x".into()),
Step::Unresponsive(Duration::from_millis(1500)),
Step::AwaitCancel,
]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200, "{text}");
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(text.contains("execution deadline"), "{text}");
// The engine is treated as lost; once it can serve again the worker attaches again by itself.
stack.wait_state(WorkerState::Ready).await;
tokio::time::sleep(Duration::from_millis(1600)).await;
stack
.engine
.push(Script::stop_with(&["fine"], usage(1, 1, 0)));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
stack.finish().await;
}
#[tokio::test]
async fn a_native_tool_call_delta_from_the_engine_is_a_protocol_violation() {
let stack = Stack::start("bw-toolviolation").await;
stack.engine.push(Script::new(vec![
Step::Text("x".into()),
Step::ToolCall {
index: 0,
id: Some("c".into()),
name: Some("lookup".into()),
arguments_delta: "{}".into(),
},
Step::AwaitCancel,
]));
let (status, text) = stack
.post("/v1/responses", &body(json!({"stream": true})))
.await;
assert_eq!(status, 200);
let events = sse_events(&text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(text.contains("tool-call delta"));
stack.finish().await;
}