Files
leleka/control-plane/tests/log_failure_sse.rs
T

196 lines
6.5 KiB
Rust

//! Charter M1 / Gate A: a failing log sink must never cut an SSE stream short of its terminal event.
//!
//! Starts the real `leleka-api` binary with a scripted engine, lets its stderr consumer disappear after startup
//! (journald or the container log driver going away makes every later write fail with EPIPE) and then provokes
//! an engine protocol failure in the middle of a streamed Responses request. The stream must still end with
//! `response.failed`, and the process must keep answering `/health`.
#![cfg(unix)]
mod common;
use std::{
io::{Read, Write},
net::TcpStream,
os::unix::fs::PermissionsExt,
process::{Child, Command, Stdio},
time::{Duration, Instant},
};
struct Server {
child: Child,
port: u16,
}
impl Drop for Server {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn http(port: u16, request: &str) -> Option<String> {
let mut stream = TcpStream::connect(("127.0.0.1", port)).ok()?;
stream
.set_read_timeout(Some(Duration::from_secs(20)))
.ok()?;
stream.write_all(request.as_bytes()).ok()?;
let mut bytes = Vec::new();
// A reset after partial data is part of what this test detects; keep what arrived.
let _ = stream.read_to_end(&mut bytes);
Some(String::from_utf8_lossy(&bytes).into_owned())
}
fn get(port: u16, path: &str) -> Option<String> {
http(
port,
&format!("GET {path} HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n\r\n"),
)
}
/// Control: with a live log consumer the same failure ends the stream and revokes readiness.
#[test]
fn sse_ends_with_response_failed_and_readiness_drops_with_a_live_log_sink() {
scenario(false);
}
#[test]
fn sse_ends_with_response_failed_when_the_log_sink_is_gone() {
scenario(true);
}
/// A shell engine: two token ids, then a line outside the wire protocol.
const ENGINE_SCRIPT: &str = concat!(
"#!/bin/sh\nprintf 'READY 262144 stop\\n'\n",
"while IFS= read -r line; do\n case \"$line\" in\n",
" GEN*) printf 'T 72\\nT 105\\nNOT-A-WIRE-LINE\\n' ;;\n",
" QUIT) exit 0 ;;\n esac\ndone\n",
);
const POST_PREFIX: &str = concat!(
"POST /v1/responses HTTP/1.1\r\nhost: localhost\r\n",
"content-type: application/json\r\ncontent-length: ",
);
const POST_SUFFIX: &str = "\r\nconnection: close\r\n\r\n";
fn write_engine(dir: &std::path::Path) -> std::path::PathBuf {
let engine = dir.join("engine.sh");
std::fs::write(&engine, ENGINE_SCRIPT).unwrap();
std::fs::set_permissions(&engine, std::fs::Permissions::from_mode(0o755)).unwrap();
engine
}
fn free_port() -> u16 {
let probe = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
probe.local_addr().unwrap().port()
}
fn spawn_server(dir: &std::path::Path, engine: &std::path::Path, port: u16) -> Child {
Command::new(env!("CARGO_BIN_EXE_leleka-api"))
.arg("serve")
.env_clear()
.env("STRATA_BIND", format!("127.0.0.1:{port}"))
.env("STRATA_ENGINE_EXE", engine)
.env("STRATA_ENGINE_ARGS_JSON", "[]")
.env("STRATA_TOKENIZER_DIR", dir.join("tokenizer"))
.env("STRATA_MODEL_ID", "fixture")
.env("STRATA_MAX_WORKER_RESTARTS", "0")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap()
}
fn wait_until_ready(port: u16) {
let started = Instant::now();
loop {
if get(port, "/ready").is_some_and(|reply| reply.starts_with("HTTP/1.1 200")) {
break;
}
assert!(
started.elapsed() < Duration::from_secs(30),
"worker never became ready"
);
std::thread::sleep(Duration::from_millis(50));
}
}
/// Provokes the engine protocol failure in the middle of a streamed Responses request.
fn post_failing_stream(port: u16) -> String {
let body = r#"{"model":"fixture","input":"hi","stream":true,"reasoning":{"effort":"none"}}"#;
let request = format!("{POST_PREFIX}{}{POST_SUFFIX}{body}", body.len());
http(port, &request).expect("the server accepted the request")
}
fn assert_failed_stream(reply: &str) {
assert!(
reply.starts_with("HTTP/1.1 200"),
"unexpected reply: {reply}"
);
assert!(
reply.contains("event: response.created"),
"stream did not start: {reply}"
);
assert!(
reply.contains("event: response.failed"),
"stream ended without a terminal event after the log sink failed: {reply}"
);
}
fn assert_alive_but_not_ready(port: u16) {
assert!(
get(port, "/health").is_some_and(|reply| reply.starts_with("HTTP/1.1 200")),
"the process stopped answering after the log sink failed"
);
// The failed worker must also be visible: no stale readiness.
assert!(
!get(port, "/ready").is_some_and(|reply| reply.starts_with("HTTP/1.1 200")),
"readiness stayed true with a failed worker"
);
}
fn scenario(sink_gone: bool) {
let dir = common::scratch(if sink_gone { "log-gone" } else { "log-live" });
let _ = common::tokenizer(&dir);
let engine = write_engine(&dir);
let port = free_port();
let mut child = spawn_server(&dir, &engine, port);
let stderr = child.stderr.take().unwrap();
let server = Server { child, port };
wait_until_ready(port);
// The log consumer goes away: from now on every write to stderr fails.
let _live_sink = if sink_gone {
drop(stderr);
None
} else {
Some(stderr)
};
assert_failed_stream(&post_failing_stream(port));
assert_alive_but_not_ready(server.port);
}
/// `eprintln!` panics when stderr is unwritable; the serving crate logs through `elog!` instead.
#[test]
fn no_panicking_log_macros_in_the_serving_crate() {
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut offenders = Vec::new();
for entry in std::fs::read_dir(&src).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_some_and(|ext| ext == "rs") {
for (number, line) in std::fs::read_to_string(&path).unwrap().lines().enumerate() {
let code = line.trim_start();
if !code.starts_with("//")
&& (code.contains("eprintln!(") || code.contains("eprint!("))
{
offenders.push(format!("{}:{}", path.display(), number + 1));
}
}
}
}
assert!(
offenders.is_empty(),
"use leleka_control_plane::elog!: {offenders:?}"
);
}