plugins/mock/x64-cpu/tests/mock.rs 11.0 KiB 383 lines Raw
1 //! The mock as a process: `--describe`, and a real job over a filesystem socket.2 3 use std::collections::BTreeMap;4 use std::fs;5 use std::io::{BufRead, BufReader};6 use std::os::unix::fs::DirBuilderExt;7 use std::os::unix::net::UnixListener;8 use std::path::{Path, PathBuf};9 use std::process::{Command, Stdio};10 use std::sync::{Arc, OnceLock};11 use std::time::Duration;12 13 use inf3r_plugin_sdk::serve::Plugin;14 use inf3r_proto::Value;15 use inf3r_proto::body::{self, Grant, Open, PartKind};16 use inf3r_proto::client::{Item, Peer};17 18 const WAIT: Duration = Duration::from_secs(10);19 20 fn bin() -> &'static str {21     env!("CARGO_BIN_EXE_inf3r-mock-x64-cpu")22 }23 24 /// The plugin that this test runs, for its catalogue.25 fn plugin() -> Arc<dyn Plugin> {26     Arc::new(mock_plugin())27 }28 29 fn mock_plugin() -> inf3r_mock_x64_cpu::MockCpu {30     inf3r_mock_x64_cpu::MockCpu::default()31 }32 33 #[test]34 fn describe_prints_twelve_capabilities_and_stops() {35     let output = Command::new(bin())36         .arg("--describe")37         .output()38         .expect("the binary runs");39     assert!(output.status.success());40     let text = String::from_utf8(output.stdout).expect("describe prints UTF-8");41 42     let value = inf3r_json::parse(&text).expect("describe prints JSON");43     let model = value44         .get("models")45         .and_then(|m| m.as_array())46         .expect("models")[0]47         .clone();48     assert_eq!(model.get("serve").and_then(|s| s.as_str()), Some("mock"));49     assert_eq!(model.get("weights_bytes").and_then(|v| v.as_i64()), Some(0));50     assert_eq!(model.get("load_ms").and_then(|v| v.as_i64()), Some(0));51     let capabilities = model52         .get("capabilities")53         .and_then(|c| c.as_object())54         .expect("capabilities");55     assert_eq!(56         capabilities.len(),57         12,58         "one capability per row of section 7"59     );60 61     for name in [62         "chat",63         "embed",64         "rerank",65         "tts",66         "stt",67         "music",68         "image-gen",69         "image-edit",70         "t2v-gen",71         "i2v-gen",72         "decide",73         "extract",74     ] {75         let capability = capabilities76             .get(name)77             .unwrap_or_else(|| panic!("no {name}"));78         assert!(79             capability.get("vocab").and_then(|v| v.as_str()).is_some(),80             "{name} has no vocab"81         );82         assert!(83             capability84                 .get("channels")85                 .and_then(|c| c.as_array())86                 .is_some_and(|c| !c.is_empty()),87             "{name} has no channels"88         );89         assert_eq!(90             capability.get("cancel").and_then(|v| v.as_str()),91             Some("token"),92             "{name} has no cancel"93         );94         assert_eq!(95             capability.get("stops").and_then(|v| v.as_str()),96             Some("plugin"),97             "{name} has no stops"98         );99         assert_eq!(100             capability.get("queue").and_then(|v| v.as_str()),101             Some("none"),102             "{name} has no queue"103         );104     }105 106     // The probe of the catalogue is honest: no device, no memory.107     assert_eq!(108         value109             .get("target")110             .and_then(|t| t.get("devices"))111             .and_then(|d| d.as_i64()),112         Some(0)113     );114 }115 116 #[test]117 fn the_plugin_answers_the_sigterm_free_shutdown_of_closing_the_socket() {118     // `--describe` must not need a socket and must not hang.119     let mut child = Command::new(bin())120         .arg("--describe")121         .stdout(Stdio::piped())122         .spawn()123         .expect("spawn");124     let stdout = child.stdout.take().expect("stdout");125     let first = BufReader::new(stdout)126         .lines()127         .next()128         .expect("a line")129         .expect("a line");130     assert!(first.starts_with('{'));131     assert!(child.wait().expect("wait").success());132 }133 134 /// A private socket directory that is removed when the test ends.135 struct SocketDir(PathBuf);136 137 impl SocketDir {138     fn new() -> SocketDir {139         static NEXT: OnceLock<std::sync::atomic::AtomicU64> = OnceLock::new();140         let next = NEXT.get_or_init(|| std::sync::atomic::AtomicU64::new(0));141         let path = Path::new("/tmp").join(format!(142             "inf3r-mock-{}-{}",143             std::process::id(),144             next.fetch_add(1, std::sync::atomic::Ordering::SeqCst)145         ));146         fs::DirBuilder::new()147             .mode(0o700)148             .create(&path)149             .expect("the private socket directory");150         SocketDir(path)151     }152 }153 154 impl Drop for SocketDir {155     fn drop(&mut self) {156         let _ = fs::remove_dir_all(&self.0);157     }158 }159 160 /// Starts the binary on a private socket and returns the connected peer.161 fn connect() -> (Peer, std::process::Child, SocketDir) {162     let dir = SocketDir::new();163     let path = dir.0.join("socket");164     let listener = UnixListener::bind(&path).expect("bind");165 166     let child = Command::new(bin())167         .arg("--socket")168         .arg(&path)169         .spawn()170         .expect("spawn");171     let (stream, _) = listener.accept().expect("accept");172     let peer = Peer::connect(stream, "mock-test", WAIT).expect("handshake");173     let grant = Grant { deps: Vec::new() };174     peer.load(&grant, WAIT).expect("load");175     (peer, child, dir)176 }177 178 fn open(capability: &str, parts: Vec<body::Part>, params: Value) -> Open {179     Open {180         request_id: "r-1".into(),181         model: "mock".into(),182         capability: capability.into(),183         credit: 1 << 20,184         budget_ms: 10_000,185         parts,186         params,187     }188 }189 190 fn text_part(role: &str, text: &str) -> body::Part {191     body::Part {192         kind: PartKind::Text,193         mime: "text/plain; charset=utf-8".into(),194         role: Some(role.into()),195         len: text.len() as u64,196         hold: body::Hold::Inline(text.as_bytes().to_vec()),197     }198 }199 200 fn json_part(role: &str, json: &str) -> body::Part {201     body::Part {202         kind: PartKind::Json,203         mime: "application/json".into(),204         role: Some(role.into()),205         len: json.len() as u64,206         hold: body::Hold::Inline(json.as_bytes().to_vec()),207     }208 }209 210 /// Reads every event and returns them with the terminal frame.211 fn run(mut job: inf3r_proto::client::Job) -> (Vec<(String, Vec<u8>)>, body::Done) {212     let mut chunks = Vec::new();213     loop {214         match job.next().expect("read").expect("an item") {215             Item::Accepted(_) => {}216             Item::Event { ch, data, .. } => chunks.push((ch, data)),217             Item::Done(done, _) => return (chunks, done),218             Item::Reject(refusal) => panic!("refused: {refusal:?}"),219         }220     }221 }222 223 #[test]224 fn chat_streams_one_chunk_per_word_and_ends_completed() {225     let (peer, mut child, _dir) = connect();226     let job = peer227         .open(228             open(229                 "chat",230                 vec![text_part("user", "hello there")],231                 Value::Map(vec![]),232             ),233             &[],234         )235         .expect("open");236 237     let (chunks, done) = run(job);238     let text: String = chunks239         .iter()240         .filter(|(ch, _)| ch == "text")241         .map(|(_, data)| String::from_utf8_lossy(data).into_owned())242         .collect();243     assert_eq!(text, "hello there ");244     assert_eq!(done.outcome, body::Outcome::Completed);245     assert_eq!(done.usage.get("tokens_out"), Some(&2));246     assert!(247         done.usage248             .get("first_token_ms")249             .is_some_and(|millis| *millis > 0)250     );251     assert!(done.usage.get("tokens_per_s").is_some_and(|rate| *rate > 0));252 253     peer.close().expect("close");254     let _ = child.kill();255     let _ = child.wait();256 }257 258 #[test]259 fn the_same_request_gives_the_same_bytes() {260     let params = Value::Map(Vec::new());261     let run_once = || {262         let (peer, mut child, _dir) = connect();263         let job = peer264             .open(265                 open(266                     "image-gen",267                     vec![text_part("prompt", "a storm")],268                     params.clone(),269                 ),270                 &[],271             )272             .expect("open");273         let (chunks, done) = run(job);274         peer.close().expect("close");275         let _ = child.kill();276         let _ = child.wait();277         (chunks, done)278     };279 280     let (first, first_done) = run_once();281     let (second, second_done) = run_once();282     assert_eq!(first, second, "the mock is a function of its input");283     assert_eq!(first_done.usage, second_done.usage);284 285     let image = first286         .iter()287         .find(|(ch, _)| ch == "image")288         .expect("an image");289     assert!(image.1.starts_with(&[0x89, b'P', b'N', b'G']), "a png");290 }291 292 #[test]293 fn a_capability_refuses_a_request_that_its_page_does_not_permit() {294     let (peer, mut child, _dir) = connect();295     // `chat` needs a `user` part; a `prompt` part is not one.296     let job = peer297         .open(298             open(299                 "chat",300                 vec![text_part("prompt", "hello")],301                 Value::Map(vec![]),302             ),303             &[],304         )305         .expect("open");306     let (_, done) = run(job);307     assert_eq!(done.outcome, body::Outcome::Failed);308     assert_eq!(309         done.meta.as_ref().and_then(|m| m.get("error")),310         Some(&Value::Text("part".into()))311     );312 313     peer.close().expect("close");314     let _ = child.kill();315     let _ = child.wait();316 }317 318 #[test]319 fn decide_and_extract_answer_the_json_of_their_pages() {320     let (peer, mut child, _dir) = connect();321 322     let options = json_part(323         "options",324         r#"{"options":[{"id":"a","label":"A"},{"id":"b","label":"B"}]}"#,325     );326     let job = peer327         .open(328             open(329                 "decide",330                 vec![text_part("question", "which?"), options],331                 Value::Map(vec![]),332             ),333             &[],334         )335         .expect("open");336     let (chunks, done) = run(job);337     assert_eq!(done.outcome, body::Outcome::Completed);338     let decision = chunks339         .iter()340         .find(|(ch, _)| ch == "decision")341         .expect("a decision");342     let value = inf3r_json::parse(std::str::from_utf8(&decision.1).unwrap()).expect("json");343     assert_eq!(value.get("chosen").and_then(|c| c.as_str()), Some("a"));344 345     let fields = json_part("fields", r#"{"fields":[{"name":"who","type":"string"}]}"#);346     let job = peer347         .open(348             open(349                 "extract",350                 vec![text_part("source", "Ada wrote it"), fields],351                 Value::Map(vec![]),352             ),353             &[],354         )355         .expect("open");356     let (chunks, _) = run(job);357     let reply = chunks358         .iter()359         .find(|(ch, _)| ch == "decision")360         .expect("a reply");361     assert_eq!(std::str::from_utf8(&reply.1).unwrap(), r#"{"who":""}"#);362 363     peer.close().expect("close");364     let _ = child.kill();365     let _ = child.wait();366 }367 368 #[test]369 fn the_catalogue_in_process_matches_describe() {370     let catalogue = plugin().catalogue();371     assert_eq!(catalogue.models.len(), 1);372     assert_eq!(catalogue.models[0].capabilities.len(), 12);373 374     let json = inf3r_plugin_sdk::catalogue_json(&catalogue);375     let value = inf3r_json::parse(&json).unwrap();376     let count = value377         .get("models")378         .and_then(|m| m.as_array())379         .and_then(|m| m[0].get("capabilities"))380         .and_then(|c| c.as_object())381         .map(BTreeMap::len);382     assert_eq!(count, Some(12));383 }