crates/edge/server/tests/engine.rs 16.2 KiB 453 lines Raw
1 //! The whole engine, as a process: deploy file, plugin, core, web, HTTP.2 //!3 //! The other tests call `App::handle` with a request in memory. This one starts4 //! `inf3r-web` the way an operator does, points it at the conformance plugin,5 //! and speaks HTTP to it. If this passes, the tree runs.6 7 use std::io::{Read, Write};8 use std::net::{TcpListener, TcpStream};9 use std::os::unix::net::UnixStream;10 use std::path::{Path, PathBuf};11 use std::process::{Child, Command, Stdio};12 use std::time::{Duration, Instant};13 14 const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";15 16 /// The target profile of the mock: a CPU bundle that any Rust host meets.17 const TARGET: &str = "[target]\nname = \"cpu\"\nbackend = \"cpu\"\narch = [\"x86_64\", \"aarch64\"]\ndevices = 0\nvram_mb = []\n";18 19 /// The target directory used by this cargo invocation.20 fn target_dir() -> PathBuf {21     let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../..");22     match std::env::var_os("CARGO_TARGET_DIR") {23         Some(dir) => {24             let dir = PathBuf::from(dir);25             if dir.is_absolute() {26                 dir27             } else {28                 root.join(dir)29             }30         }31         None => root.join("target"),32     }33 }34 35 /// The plugin binary that cargo built for this test run.36 fn plugin_bin() -> PathBuf {37     target_dir().join("debug/inf3r-mock-x64-cpu")38 }39 40 /// The operator binary that cargo builds beside the web.41 fn cli_bin() -> PathBuf {42     target_dir().join("debug/inf3r")43 }44 45 struct Engine {46     child: Child,47     dir: PathBuf,48     port: Option<u16>,49     socket: Option<PathBuf>,50 }51 52 /// The listeners that one test starts.53 #[derive(Clone, Copy, PartialEq, Eq)]54 enum Transport {55     Tcp,56     Both,57 }58 59 impl Drop for Engine {60     fn drop(&mut self) {61         let _ = self.child.kill();62         let _ = self.child.wait();63         let _ = std::fs::remove_dir_all(&self.dir);64     }65 }66 67 fn start() -> Engine {68     start_with(true, None)69 }70 71 fn start_with(warm: bool, idle_unload: Option<&str>) -> Engine {72     start_engine(warm, idle_unload, Transport::Tcp)73 }74 75 fn start_unix_and_tcp() -> Engine {76     start_engine(true, None, Transport::Both)77 }78 79 fn start_engine(warm: bool, idle_unload: Option<&str>, transport: Transport) -> Engine {80     let plugin = plugin_bin();81     assert!(82         plugin.exists(),83         "build the mock first: {} is missing",84         plugin.display()85     );86 87     static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);88     let dir = std::env::temp_dir().join(format!(89         "inf3r-engine-{}-{}",90         std::process::id(),91         NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)92     ));93     let _ = std::fs::remove_dir_all(&dir);94     std::fs::create_dir_all(dir.join("bin")).expect("bin");95     std::fs::create_dir_all(dir.join("blobs")).expect("blobs");96 97     // The rule of section 17: `mock/x64-cpu` runs `bin_dir/inf3r-mock-x64-cpu`.98     std::fs::copy(&plugin, dir.join("bin/inf3r-mock-x64-cpu")).expect("copy");99     std::fs::write(dir.join("token"), format!("{TOKEN}\n")).expect("token");100     let bundles = dir.join("plugins");101     std::fs::create_dir_all(bundles.join("mock/x64-cpu")).expect("bundle");102     std::fs::write(bundles.join("mock/x64-cpu/target.toml"), TARGET).expect("target");103 104     // A free port: bind, ask, close, then hand the number to the engine.105     let port = match transport {106         Transport::Tcp | Transport::Both => {107             let listener = TcpListener::bind("127.0.0.1:0").expect("bind");108             let port = listener.local_addr().expect("addr").port();109             drop(listener);110             Some(port)111         }112     };113     let socket = match transport {114         Transport::Tcp => None,115         Transport::Both => Some(dir.join("web.sock")),116     };117     let web = match (&socket, port) {118         (Some(socket), Some(port)) => {119             format!(120                 "{{ unix = \"{}\", tcp = \"127.0.0.1:{port}\" }}",121                 socket.display()122             )123         }124         (Some(socket), None) => format!("{{ unix = \"{}\" }}", socket.display()),125         (None, Some(port)) => format!("{{ tcp = \"127.0.0.1:{port}\" }}"),126         (None, None) => unreachable!("a test starts at least one listener"),127     };128 129     let mut extra = String::new();130     if !warm {131         extra.push_str("warm = false\n");132     }133     if let Some(idle) = idle_unload {134         extra.push_str(&format!("idle_unload = \"{idle}\"\n"));135     }136     let deploy = format!(137         r#"138 [[node]]139 host        = "test"140 bin_dir     = "{}"141 bundle_dirs = ["{}"]142 blob_dir    = "{}"143 web         = {web}144 auth_file  = "{}"145 settle      = "100ms"146 147 [[node.bind]]148 bundle   = "mock/x64-cpu"149 models   = ["mock"]150 devices  = ["cpu:0"]151 vram     = [1048576]152 {extra}"#,153         dir.join("bin").display(),154         bundles.display(),155         dir.join("blobs").display(),156         dir.join("token").display(),157     );158     std::fs::write(dir.join("deploy.toml"), deploy).expect("deploy");159 160     #[allow(clippy::zombie_processes)]161     let child = Command::new(env!("CARGO_BIN_EXE_inf3r-web"))162         .env(163             "INF3R_RUN_DIR",164             std::path::Path::new("/tmp").join(format!("inf3r-web-run-{}", std::process::id())),165         )166         .arg("--deploy")167         .arg(dir.join("deploy.toml"))168         .stdout(Stdio::null())169         .stderr(Stdio::null())170         .spawn()171         .expect("spawn inf3r-web");172 173     // Wait for every configured listener.174     let started = Instant::now();175     let tcp_ready = |port: u16| TcpStream::connect(("127.0.0.1", port)).is_ok();176     let unix_ready = |socket: &Path| UnixStream::connect(socket).is_ok();177     while started.elapsed() < Duration::from_secs(30) {178         let tcp_done = port.is_none_or(tcp_ready);179         let unix_done = socket.as_deref().is_none_or(unix_ready);180         if tcp_done && unix_done {181             return Engine {182                 child,183                 dir,184                 port,185                 socket,186             };187         }188         std::thread::sleep(Duration::from_millis(20));189     }190     panic!("inf3r-web did not listen on {:?}", dir.join("web.sock"));191 }192 193 impl Engine {194     fn request(&self, request: &str) -> String {195         let port = self.port.expect("the TCP listener");196         let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect");197         // A stalled credit window would otherwise hang the test forever.198         stream199             .set_read_timeout(Some(Duration::from_secs(60)))200             .expect("timeout");201         stream.write_all(request.as_bytes()).expect("write");202         let mut response = String::new();203         stream.read_to_string(&mut response).expect("read");204         response205     }206 207     fn get(&self, target: &str, auth: bool) -> String {208         let header = if auth {209             format!("Authorization: Bearer {TOKEN}\r\n")210         } else {211             String::new()212         };213         self.request(&format!(214             "GET {target} HTTP/1.1\r\nHost: x\r\n{header}Connection: close\r\n\r\n"215         ))216     }217 218     fn post(&self, target: &str, body: &str) -> String {219         self.request(&format!(220             "POST {target} HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",221             body.len()222         ))223     }224 }225 226 #[test]227 fn the_engine_serves_health_and_a_streamed_chat() {228     let engine = start();229 230     let health = engine.get("/healthz", false);231     assert!(health.starts_with("HTTP/1.1 200 OK"), "{health}");232 233     let unauthorized = engine.get("/models", false);234     assert!(unauthorized.starts_with("HTTP/1.1 401"), "{unauthorized}");235 236     let models = engine.get("/models", true);237     assert!(models.starts_with("HTTP/1.1 200 OK"), "{models}");238     assert!(models.contains(r#""serve":"mock""#), "{models}");239     assert!(models.contains(r#""name":"chat""#), "{models}");240 241     let body =242         r#"{"model":"mock","input":[{"kind":"text","role":"user","text":"hello"}],"stream":true}"#;243     let reply = engine.post("/chat", body);244     assert!(reply.starts_with("HTTP/1.1 200 OK"), "{reply}");245     assert!(reply.contains("text/event-stream"), "{reply}");246     assert!(reply.contains(r#""t":"started""#), "{reply}");247     assert!(reply.contains(r#""t":"done""#), "{reply}");248     assert!(reply.contains("data: [DONE]\n\n"), "{reply}");249     // The chunked body ends with the zero chunk, and no more.250     assert!(reply.ends_with("0\r\n\r\n"), "{reply}");251 }252 253 #[test]254 fn a_cold_bind_loads_on_first_use_and_reloads_after_an_idle_unload() {255     let engine = start_with(false, Some("100ms"));256 257     // Discovery ran `--describe`, not a load: the name is already in the258     // catalog and the stats route must report it without a peer.259     let models = engine.get("/models", true);260     assert!(models.starts_with("HTTP/1.1 200 OK"), "{models}");261     assert!(models.contains(r#""serve":"mock""#), "{models}");262     let stats = engine.get("/stats", true);263     assert!(stats.starts_with("HTTP/1.1 200 OK"), "{stats}");264     assert!(stats.contains(r#""model":"mock""#), "{stats}");265 266     let body =267         r#"{"model":"mock","input":[{"kind":"text","role":"user","text":"cold"}],"stream":false}"#;268     let first = engine.post("/chat", body);269     assert!(first.starts_with("HTTP/1.1 200 OK"), "{first}");270     assert!(first.contains(r#""status":"completed""#), "{first}");271 272     // The idle sweep runs once a second; the settle budget is 100 ms. Waiting273     // past both proves that the child was stopped, not merely that it was274     // never loaded.275     std::thread::sleep(Duration::from_millis(1600));276     let after = engine.get("/stats", true);277     assert!(after.starts_with("HTTP/1.1 200 OK"), "{after}");278     assert!(after.contains(r#""engines":[]"#), "{after}");279 280     let second = engine.post("/chat", body);281     assert!(second.starts_with("HTTP/1.1 200 OK"), "{second}");282     assert!(second.contains(r#""status":"completed""#), "{second}");283 }284 285 #[test]286 fn a_stream_larger_than_two_windows_is_replenished() {287     let engine = start();288     // 20 MiB is more than two 8 MiB windows. The mock blocks when the first289     // window is spent, so this reply only finishes if the web grants credit as290     // it consumes the text.291     let body = r#"{"model":"mock","input":[{"kind":"text","role":"user","text":"hello"}],"params":{"bytes":20971520},"stream":false}"#;292     let reply = engine.post("/chat", body);293     assert!(reply.starts_with("HTTP/1.1 200 OK"), "{reply:.200}");294     assert!(reply.contains(r#""status":"completed""#), "{reply:.200}");295     assert!(296         reply.len() > 20 * 1024 * 1024,297         "the whole stream arrived ({} bytes)",298         reply.len()299     );300 }301 302 #[test]303 fn an_openai_request_reaches_the_same_job_handler() {304     let engine = start();305     let body = r#"{"model":"mock","messages":[{"role":"user","content":"hi"}],"stream":true}"#;306     let reply = engine.post("/openai/v1/chat/completions", body);307     assert!(reply.starts_with("HTTP/1.1 200 OK"), "{reply}");308     assert!(309         reply.contains(r#""object":"chat.completion.chunk""#),310         "{reply}"311     );312     assert!(reply.contains(r#""finish_reason":"stop""#), "{reply}");313     assert!(reply.contains("data: [DONE]"), "{reply}");314 }315 316 #[test]317 fn the_operator_cli_authenticates_over_the_unix_socket_while_tcp_serves() {318     let engine = start_unix_and_tcp();319     let socket = engine.socket.as_deref().expect("the Unix socket");320 321     // Both listeners reach the same app. The TCP route proves that enabling322     // the Unix socket did not replace the other listener.323     let remote = engine.get("/models", true);324     assert!(remote.starts_with("HTTP/1.1 200 OK"), "{remote}");325 326     let cli = cli_bin();327     assert!(328         cli.exists(),329         "build the operator first: {} is missing",330         cli.display()331     );332     for command in ["models", "stats", "ps", "queue"] {333         let output = Command::new(&cli)334             .arg("--socket")335             .arg(socket)336             .arg(command)337             .output()338             .expect("the operator command");339         assert!(340             output.status.success(),341             "inf3r {command} failed: {}",342             String::from_utf8_lossy(&output.stderr)343         );344         if command == "models" {345             let stdout = String::from_utf8_lossy(&output.stdout);346             assert!(stdout.contains("mock"), "{stdout}");347         }348     }349 }350 351 #[test]352 fn sigterm_ends_the_process_through_the_drain() {353     let mut engine = start_unix_and_tcp();354     // The handler exits with success when the drain finishes. A process that355     // never installed the handler would die of the signal instead.356     let pid = rustix::process::Pid::from_raw(i32::try_from(engine.child.id()).expect("a pid"))357         .expect("a pid");358     rustix::process::kill_process(pid, rustix::process::Signal::TERM).expect("send SIGTERM");359 360     // The supervisor's grace is ten seconds and the plugin is told to stop361     // first. A process that needs the grace to expire has not closed the362     // plugin's socket, which is the bug that a drop without shutdown causes.363     let started = Instant::now();364     while started.elapsed() < Duration::from_secs(30) {365         match engine.child.try_wait() {366             Ok(Some(status)) => {367                 assert!(status.success(), "{status}");368                 assert!(369                     started.elapsed() < Duration::from_secs(5),370                     "the drain took {:?}",371                     started.elapsed()372                 );373                 return;374             }375             Ok(None) => std::thread::sleep(Duration::from_millis(20)),376             Err(why) => panic!("wait: {why}"),377         }378     }379     panic!("inf3r-web did not stop after SIGTERM");380 }381 382 /// The processes whose parent is `pid`, from the kernel's own list.383 fn children_of(pid: u32) -> Vec<u32> {384     let path = format!("/proc/{pid}/task/{pid}/children");385     let text = std::fs::read_to_string(path).unwrap_or_default();386     text.split_whitespace()387         .filter_map(|field| field.parse().ok())388         .collect()389 }390 391 /// Waits until the engine reports a job in flight and returns the plugin pid.392 fn wait_for_child(engine: &Engine, started: Instant) -> u32 {393     while started.elapsed() < Duration::from_secs(20) {394         let stats = engine.get("/stats", true);395         if stats.contains(r#""in_flight":1"#)396             && let Some(pid) = children_of(engine.child.id()).first()397         {398             return *pid;399         }400         std::thread::sleep(Duration::from_millis(20));401     }402     panic!("the plugin never took the job");403 }404 405 /// Waits until the dead peer has left `/stats` and its reservation is free.406 fn wait_for_release(engine: &Engine, started: Instant) {407     while started.elapsed() < Duration::from_secs(20) {408         let stats = engine.get("/stats", true);409         if stats.contains(r#""engines":[]"#) && stats.contains(r#""used":0"#) {410             return;411         }412         std::thread::sleep(Duration::from_millis(20));413     }414     panic!("the dead plugin did not release the ledger");415 }416 417 #[test]418 fn a_killed_plugin_fails_its_job_and_reloads_on_the_next_request() {419     let engine = start();420     let body = r#"{"model":"mock","input":[{"kind":"text","role":"user","text":"lost"}],"params":{"bytes":67108864},"stream":true}"#;421     let request = format!(422         "POST /chat HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",423         body.len()424     );425     let mut stream =426         TcpStream::connect(("127.0.0.1", engine.port.expect("the TCP listener"))).expect("connect");427     stream428         .set_read_timeout(Some(Duration::from_secs(30)))429         .expect("timeout");430     let started = Instant::now();431     stream432         .write_all(request.as_bytes())433         .expect("write the request");434     let pid = wait_for_child(&engine, started);435     let signal = rustix::process::Signal::KILL;436     let target = rustix::process::Pid::from_raw(i32::try_from(pid).expect("pid")).expect("pid");437     rustix::process::kill_process(target, signal).expect("kill the plugin");438 439     let mut reply = String::new();440     stream441         .read_to_string(&mut reply)442         .expect("read the failed stream");443     assert!(reply.contains("plugin_crashed"), "{reply:.500}");444 445     let released = Instant::now();446     wait_for_release(&engine, released);447 448     let body =449         r#"{"model":"mock","input":[{"kind":"text","role":"user","text":"again"}],"stream":false}"#;450     let recovered = engine.post("/chat", body);451     assert!(recovered.starts_with("HTTP/1.1 200 OK"), "{recovered}");452     assert!(recovered.contains(r#""status":"completed""#), "{recovered}");453 }