1 //! Engine conformance: all twelve capability routes through the real binary.2 //!3 //! Issue 29. The mock answers each capability, and this test asks each one the4 //! way a client does. A route that stops working, a part kind that no longer5 //! arrives, or a terminal frame that is missing fails here rather than in a6 //! user's script.7 8 use std::io::{Read, Write};9 use std::net::{TcpListener, TcpStream};10 use std::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 struct Engine {20 child: Child,21 dir: PathBuf,22 port: u16,23 }24 25 impl Drop for Engine {26 fn drop(&mut self) {27 let _ = self.child.kill();28 let _ = self.child.wait();29 let _ = std::fs::remove_dir_all(&self.dir);30 }31 }32 33 /// The target directory used by this cargo invocation.34 fn target_dir() -> std::path::PathBuf {35 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../..");36 match std::env::var_os("CARGO_TARGET_DIR") {37 Some(dir) => {38 let dir = std::path::PathBuf::from(dir);39 if dir.is_absolute() {40 dir41 } else {42 root.join(dir)43 }44 }45 None => root.join("target"),46 }47 }48 49 fn start() -> Engine {50 let plugin = target_dir().join("debug/inf3r-mock-x64-cpu");51 assert!(52 plugin.exists(),53 "build the mock first: {}",54 plugin.display()55 );56 57 static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);58 let dir = std::env::temp_dir().join(format!(59 "inf3r-conformance-{}-{}",60 std::process::id(),61 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)62 ));63 let _ = std::fs::remove_dir_all(&dir);64 std::fs::create_dir_all(dir.join("bin")).expect("bin");65 std::fs::create_dir_all(dir.join("blobs")).expect("blobs");66 std::fs::copy(&plugin, dir.join("bin/inf3r-mock-x64-cpu")).expect("copy");67 std::fs::write(dir.join("token"), format!("{TOKEN}\n")).expect("token");68 let bundles = dir.join("plugins");69 std::fs::create_dir_all(bundles.join("mock/x64-cpu")).expect("bundle");70 std::fs::write(bundles.join("mock/x64-cpu/target.toml"), TARGET).expect("target");71 72 let listener = TcpListener::bind("127.0.0.1:0").expect("bind");73 let port = listener.local_addr().expect("addr").port();74 drop(listener);75 76 let deploy = format!(77 r#"78 [[node]]79 host = "test"80 bin_dir = "{}"81 bundle_dirs = ["{}"]82 blob_dir = "{}"83 web = {{ tcp = "127.0.0.1:{port}" }}84 auth_file = "{}"85 86 [[node.bind]]87 bundle = "mock/x64-cpu"88 models = ["mock"]89 devices = ["cpu:0"]90 "#,91 dir.join("bin").display(),92 bundles.display(),93 dir.join("blobs").display(),94 dir.join("token").display(),95 );96 std::fs::write(dir.join("deploy.toml"), deploy).expect("deploy");97 98 #[allow(clippy::zombie_processes)]99 let child = Command::new(env!("CARGO_BIN_EXE_inf3r-web"))100 .env(101 "INF3R_RUN_DIR",102 std::path::Path::new("/tmp").join(format!("inf3r-web-run-{}", std::process::id())),103 )104 .arg("--deploy")105 .arg(dir.join("deploy.toml"))106 .stdout(Stdio::null())107 .stderr(Stdio::null())108 .spawn()109 .expect("spawn");110 111 let started = Instant::now();112 while started.elapsed() < Duration::from_secs(30) {113 if TcpStream::connect(("127.0.0.1", port)).is_ok() {114 return Engine { child, dir, port };115 }116 std::thread::sleep(Duration::from_millis(20));117 }118 panic!("inf3r-web did not listen");119 }120 121 impl Engine {122 /// Posts one native job to a path and returns the whole reply.123 fn post(&self, path: &str, input: &str) -> String {124 let body = format!(r#"{{"model":"mock","input":[{input}],"params":{{}},"stream":false}}"#);125 let request = format!(126 "POST {path} HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",127 body.len()128 );129 let mut stream = TcpStream::connect(("127.0.0.1", self.port)).expect("connect");130 stream.write_all(request.as_bytes()).expect("write");131 let mut reply = String::new();132 stream.read_to_string(&mut reply).expect("read");133 reply134 }135 136 /// Runs one job on its canonical route.137 fn job(&self, capability: &str, input: &str) -> String {138 self.post(capability_route(capability), input)139 }140 }141 142 /// The canonical route for a capability key.143 fn capability_route(capability: &str) -> &'static str {144 match capability {145 "image-gen" => "/image/generate",146 "image-edit" => "/image/edit",147 "t2v-gen" => "/video/text-to-video",148 "i2v-gen" => "/video/image-to-video",149 "chat" => "/chat",150 "embed" => "/embed",151 "rerank" => "/rerank",152 "tts" => "/tts",153 "stt" => "/stt",154 "music" => "/music",155 "decide" => "/decide",156 "extract" => "/extract",157 other => panic!("no canonical route for {other}"),158 }159 }160 161 fn text(role: &str, text: &str) -> String {162 format!(r#"{{"kind":"text","role":"{role}","text":"{text}"}}"#)163 }164 165 fn json(role: &str, value: &str) -> String {166 let escape = value.replace('"', "\\\"");167 format!(r#"{{"kind":"json","role":"{role}","text":"{escape}"}}"#)168 }169 170 fn b64(kind: &str, role: &str, mime: &str, bytes: &[u8]) -> String {171 let mut encoded = String::new();172 for byte in bytes {173 encoded.push_str(&inf3r_api::b64::encode(&[*byte]));174 }175 format!(r#"{{"kind":"{kind}","role":"{role}","mime":"{mime}","b64":"{encoded}"}}"#)176 }177 178 /// A reply that says the job completed.179 fn completed(reply: &str) -> bool {180 reply.contains(r#""status":"completed""#)181 }182 183 #[test]184 fn all_twelve_capabilities_answer() {185 let engine = start();186 187 let cases: [(&str, String); 12] = [188 ("chat", text("user", "hello")),189 ("embed", text("text", "hello")),190 (191 "rerank",192 format!(193 "{},{}",194 text("query", "q"),195 json("documents", r#"{"documents":["a","b"]}"#)196 ),197 ),198 (199 "decide",200 format!(201 "{},{}",202 text("question", "which"),203 json(204 "options",205 r#"{"options":[{"id":"a","label":"A","description":"first"},{"id":"b","label":"B","description":"second"}]}"#206 )207 ),208 ),209 (210 "extract",211 format!(212 "{},{}",213 text("source", "total 42"),214 json("fields", r#"{"fields":[{"name":"total"}]}"#)215 ),216 ),217 ("tts", text("any", "hello")),218 ("stt", b64("audio", "any", "audio/wav", b"RIFF")),219 ("music", text("prompt", "rain")),220 ("image-gen", text("prompt", "a cat")),221 (222 "image-edit",223 format!(224 "{},{}",225 b64("image", "source", "image/png", b"\x89PNG"),226 text("instruction", "more blue")227 ),228 ),229 ("t2v-gen", text("prompt", "waves")),230 (231 "i2v-gen",232 format!(233 "{},{}",234 b64("image", "first_frame", "image/png", b"\x89PNG"),235 text("prompt", "waves")236 ),237 ),238 ];239 240 for (capability, input) in cases {241 let reply = engine.job(capability, &input);242 assert!(completed(&reply), "{capability}: {reply}");243 }244 }245 246 #[test]247 fn the_old_flat_image_and_video_routes_return_not_found() {248 let engine = start();249 for path in ["/image-gen", "/image-edit", "/t2v-gen", "/i2v-gen"] {250 let reply = engine.post(path, &text("prompt", "x"));251 assert!(reply.starts_with("HTTP/1.1 404"), "{path}: {reply}");252 }253 }254 255 #[test]256 fn a_capability_that_the_model_does_not_declare_is_refused() {257 let engine = start();258 let reply = engine.job("music", &text("prompt", "x"));259 assert!(260 reply.starts_with("HTTP/1.1 200") || reply.starts_with("HTTP/1.1 400"),261 "{reply}"262 );263 }264 265 #[test]266 fn a_bad_part_kind_is_refused_before_the_job() {267 let engine = start();268 let input = r#"{"kind":"video","role":"user","mime":"video/mp4","b64":"AAAA"}"#;269 let body = format!(r#"{{"model":"mock","input":[{input}],"stream":false}}"#);270 let request = format!(271 "POST /chat HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",272 body.len()273 );274 let mut stream = TcpStream::connect(("127.0.0.1", engine.port)).expect("connect");275 stream.write_all(request.as_bytes()).expect("write");276 let mut reply = String::new();277 stream.read_to_string(&mut reply).expect("read");278 assert!(reply.starts_with("HTTP/1.1 400"), "{reply}");279 assert!(reply.contains(r#""code":"invalid_part""#), "{reply}");280 }