1 //! The runner against a real plugin, a faulty one, and a stub.2 3 use std::collections::BTreeMap;4 use std::os::unix::net::UnixListener;5 use std::path::PathBuf;6 use std::process::Command;7 use std::sync::atomic::{AtomicU64, Ordering};8 use std::thread;9 use std::time::{Duration, Instant};10 11 use inf3r_proto::body::{12 self, Body, Cancel, Capability, Catalogue, Model, PartKind, Queue, Stops, Target,13 };14 use inf3r_proto::{Header, Kind, recv_frame, send_frame};15 use inf3r_verify::{State, Verify};16 17 /// The twelve capabilities that the mock declares.18 const MOCK_CAPABILITIES: [&str; 12] = [19 "chat",20 "embed",21 "rerank",22 "decide",23 "extract",24 "tts",25 "stt",26 "music",27 "image-gen",28 "image-edit",29 "t2v-gen",30 "i2v-gen",31 ];32 33 fn binary(name: &str) -> PathBuf {34 let mut path = std::env::current_exe().expect("the test binary has a path");35 path.pop();36 if path.file_name().is_some_and(|name| name == "deps") {37 path.pop();38 }39 path.join(name)40 }41 42 #[test]43 fn the_mock_passes_every_check() {44 let report = Verify::command(Command::new(binary("inf3r-mock-x64-cpu")))45 .budget(Duration::from_secs(20))46 .run()47 .expect("the runner returns a report");48 49 assert!(50 report.checks.iter().all(|check| check.state != State::Fail),51 "{report}"52 );53 for name in MOCK_CAPABILITIES {54 assert!(55 report56 .checks57 .iter()58 .any(|check| check.name == name && check.state == State::Pass),59 "no passing job check for {name}: {report}"60 );61 }62 for name in [63 "cache_fingerprint",64 "cache_cold_erase",65 "cache_roundtrip",66 "cache_corrupt_fallback",67 "cache_abort_on_crash",68 ] {69 let check = report70 .checks71 .iter()72 .find(|check| check.name == name)73 .unwrap_or_else(|| panic!("no {name} check: {report}"));74 assert_eq!(check.state, State::Pass, "{report}");75 }76 assert_eq!(report.exit_code(), 0);77 }78 79 #[test]80 fn the_toy_passes_chat_when_the_weights_travel_as_a_descriptor() {81 let path = toy_weights();82 let report = Verify::command(Command::new(binary("inf3r-toy-x64-cpu")))83 .weights(path.clone())84 .budget(Duration::from_secs(20))85 .run()86 .expect("the runner returns a report");87 88 let chat = report89 .checks90 .iter()91 .find(|check| check.name == "chat")92 .expect("a chat check");93 assert_eq!(chat.state, State::Pass, "{report}");94 assert!(95 report.checks.iter().all(|check| check.state != State::Fail),96 "{report}"97 );98 assert_eq!(report.exit_code(), 0);99 let _ = std::fs::remove_file(&path);100 }101 102 #[test]103 fn a_refused_load_skips_the_jobs_and_exits_zero() {104 let path = socket_path();105 let _ = std::fs::remove_file(&path);106 let listener = UnixListener::bind(&path).expect("bind the stub socket");107 let stub = thread::spawn(move || serve_stub_refusing_load(listener));108 109 let report = Verify::socket(path.to_str().expect("a UTF-8 path"))110 .budget(Duration::from_secs(5))111 .run()112 .expect("the runner returns a report");113 114 for name in ["chat", "cancel", "credit"] {115 let check = report116 .checks117 .iter()118 .find(|check| check.name == name)119 .expect("a check for the capability");120 assert_eq!(check.state, State::Skip, "{report}");121 assert_eq!(check.detail, "load refused: no room");122 }123 assert!(124 report.checks.iter().all(|check| check.state != State::Fail),125 "{report}"126 );127 assert_eq!(report.exit_code(), 0);128 129 let _ = stub.join();130 let _ = std::fs::remove_file(&path);131 }132 133 #[test]134 fn a_stalled_or_silent_mock_fails_in_a_two_second_budget() {135 for mode in ["stall", "silent"] {136 let started = Instant::now();137 let mut command = Command::new(binary("inf3r-mock-fault"));138 command.args(["--fault", mode]);139 let report = Verify::command(command)140 .budget(Duration::from_secs(2))141 .run()142 .expect("the runner returns a report");143 144 assert!(145 report.checks.iter().any(|check| check.state == State::Fail),146 "{mode} produced no fail: {report}"147 );148 assert_eq!(report.exit_code(), 1);149 assert!(150 started.elapsed() < Duration::from_secs(6),151 "{mode} took {:?}",152 started.elapsed()153 );154 }155 }156 157 #[test]158 fn a_command_that_exits_before_connecting_fails_at_once() {159 let started = Instant::now();160 let report = Verify::command(Command::new("false"))161 .budget(Duration::from_secs(20))162 .run()163 .expect("the runner returns a report");164 let handshake = report165 .checks166 .iter()167 .find(|check| check.name == "handshake")168 .expect("a handshake check");169 assert_eq!(handshake.state, State::Fail, "{report}");170 assert!(171 started.elapsed() < Duration::from_secs(2),172 "the gate spun for {:?}",173 started.elapsed()174 );175 assert_eq!(report.exit_code(), 1);176 }177 178 #[test]179 fn a_declared_capability_that_is_refused_is_a_skip() {180 let path = socket_path();181 let _ = std::fs::remove_file(&path);182 let listener = UnixListener::bind(&path).expect("bind the stub socket");183 let stub = thread::spawn(move || serve_stub(listener));184 185 let report = Verify::socket(path.to_str().expect("a UTF-8 path"))186 .budget(Duration::from_secs(5))187 .run()188 .expect("the runner returns a report");189 190 let chat = report191 .checks192 .iter()193 .find(|check| check.name == "chat")194 .expect("a chat check");195 assert_eq!(chat.state, State::Skip);196 assert_eq!(chat.detail, "not implemented by this binding");197 assert!(198 report.checks.iter().all(|check| check.state != State::Fail),199 "{report}"200 );201 202 let _ = stub.join();203 let _ = std::fs::remove_file(&path);204 }205 206 #[test]207 fn a_degraded_capability_skips_cancel_but_still_checks_credit() {208 let path = socket_path();209 let _ = std::fs::remove_file(&path);210 let listener = UnixListener::bind(&path).expect("bind the stub socket");211 let stub =212 thread::spawn(move || serve_stub_with(listener, stub_catalogue_with(Cancel::Request)));213 214 let report = Verify::socket(path.to_str().expect("a UTF-8 path"))215 .budget(Duration::from_secs(5))216 .run()217 .expect("the runner returns a report");218 219 let cancel = report220 .checks221 .iter()222 .find(|check| check.name == "cancel")223 .expect("a cancel check");224 assert_eq!(cancel.state, State::Skip);225 assert_eq!(226 cancel.detail,227 "declared cancel request; the engine stops at that boundary"228 );229 let credit = report230 .checks231 .iter()232 .find(|check| check.name == "credit")233 .unwrap_or_else(|| panic!("no credit check: {report}"));234 // `cancel: request` does not imply an internal queue. The credit check235 // still runs; this stub refuses every job before accepting it.236 assert_eq!(credit.state, State::Skip);237 assert_eq!(credit.detail, "not implemented by this binding");238 assert!(239 report.checks.iter().all(|check| check.state != State::Fail),240 "{report}"241 );242 assert_eq!(report.exit_code(), 0);243 244 let _ = stub.join();245 let _ = std::fs::remove_file(&path);246 }247 248 #[test]249 fn display_prints_one_line_per_check() {250 let path = socket_path();251 let _ = std::fs::remove_file(&path);252 let listener = UnixListener::bind(&path).expect("bind the stub socket");253 let stub = thread::spawn(move || serve_stub(listener));254 255 let report = Verify::socket(path.to_str().expect("a UTF-8 path"))256 .budget(Duration::from_secs(5))257 .run()258 .expect("the runner returns a report");259 let text = report.to_string();260 assert_eq!(text.lines().count(), report.checks.len());261 assert!(text.contains("skip chat: not implemented by this binding"));262 263 let _ = stub.join();264 let _ = std::fs::remove_file(&path);265 }266 267 #[test]268 fn a_one_step_suite_judges_one_capability() {269 let path = socket_path();270 let _ = std::fs::remove_file(&path);271 let listener = UnixListener::bind(&path).expect("bind the stub socket");272 let stub = thread::spawn(move || serve_stub(listener));273 let suite = suite_file(274 r#"{"steps":[{"capability":"chat","parts":[{"kind":"text","text":"hello"}],"expect":"completed"}]}"#,275 );276 277 let report = Verify::socket(path.to_str().expect("a UTF-8 path"))278 .suite(&suite)279 .budget(Duration::from_secs(5))280 .run()281 .expect("the runner returns a report");282 283 let chat: Vec<_> = report284 .checks285 .iter()286 .filter(|check| check.name == "chat")287 .collect();288 assert_eq!(chat.len(), 2, "{report}");289 assert_eq!(report.checks.len(), 9, "{report}");290 291 let _ = stub.join();292 let _ = std::fs::remove_file(&path);293 let _ = std::fs::remove_file(&suite);294 }295 296 #[test]297 fn a_suite_step_for_an_undeclared_capability_is_a_skip() {298 let path = socket_path();299 let _ = std::fs::remove_file(&path);300 let listener = UnixListener::bind(&path).expect("bind the stub socket");301 let stub = thread::spawn(move || serve_stub(listener));302 let suite = suite_file(303 r#"{"steps":[{"capability":"nosuch","parts":[{"kind":"text","text":"hello"}],"expect":"completed"}]}"#,304 );305 306 let report = Verify::socket(path.to_str().expect("a UTF-8 path"))307 .suite(&suite)308 .budget(Duration::from_secs(5))309 .run()310 .expect("the runner returns a report");311 312 let check = report313 .checks314 .iter()315 .find(|check| check.name == "nosuch")316 .expect("a step check");317 assert_eq!(check.state, State::Skip);318 assert_eq!(check.detail, "not declared");319 let chat = report320 .checks321 .iter()322 .find(|check| check.name == "chat")323 .expect("a chat check");324 assert_eq!(chat.state, State::Skip);325 assert_eq!(chat.detail, "not in the suite");326 327 let _ = stub.join();328 let _ = std::fs::remove_file(&path);329 let _ = std::fs::remove_file(&suite);330 }331 332 /// Writes the toy's generated GGUF: two tokens, a stop, and an embedding that333 /// selects token 1 from the prompt `A`.334 fn toy_weights() -> PathBuf {335 static NEXT: AtomicU64 = AtomicU64::new(1);336 const ALIGN: usize = 32;337 const WIDTH: usize = 8;338 let vocab = ["x", "a"];339 let mut out = Vec::new();340 out.extend_from_slice(b"GGUF");341 out.extend_from_slice(&3u32.to_le_bytes());342 out.extend_from_slice(&1u64.to_le_bytes());343 out.extend_from_slice(&2u64.to_le_bytes());344 push_str(&mut out, "toy.vocab");345 out.extend_from_slice(&12u32.to_le_bytes());346 out.extend_from_slice(&11u32.to_le_bytes());347 out.extend_from_slice(&(vocab.len() as u64).to_le_bytes());348 for token in vocab {349 push_str(&mut out, token);350 }351 push_str(&mut out, "toy.stop");352 out.extend_from_slice(&11u32.to_le_bytes());353 push_str(&mut out, "zzz");354 push_str(&mut out, "embed");355 out.extend_from_slice(&2u32.to_le_bytes());356 out.extend_from_slice(&(vocab.len() as u64).to_le_bytes());357 out.extend_from_slice(&(WIDTH as u64).to_le_bytes());358 out.extend_from_slice(&0u32.to_le_bytes());359 out.extend_from_slice(&0u64.to_le_bytes());360 let rem = out.len() % ALIGN;361 if rem != 0 {362 out.resize(out.len() + (ALIGN - rem), 0);363 }364 for token in 0..vocab.len() {365 for position in 0..WIDTH {366 let value = if token == 1 && position == 0 {367 1.0f32368 } else {369 0.0f32370 };371 out.extend_from_slice(&value.to_le_bytes());372 }373 }374 let path = std::env::temp_dir().join(format!(375 "inf3r-verify-weights-{}-{}.gguf",376 std::process::id(),377 NEXT.fetch_add(1, Ordering::Relaxed)378 ));379 std::fs::write(&path, out).expect("write the generated GGUF");380 path381 }382 383 fn push_str(out: &mut Vec<u8>, text: &str) {384 out.extend_from_slice(&(text.len() as u64).to_le_bytes());385 out.extend_from_slice(text.as_bytes());386 }387 388 fn suite_file(json: &str) -> PathBuf {389 static NEXT: AtomicU64 = AtomicU64::new(1);390 let path = std::env::temp_dir().join(format!(391 "inf3r-verify-suite-{}-{}.json",392 std::process::id(),393 NEXT.fetch_add(1, Ordering::Relaxed)394 ));395 std::fs::write(&path, json).expect("write the suite file");396 path397 }398 399 fn socket_path() -> PathBuf {400 static NEXT: AtomicU64 = AtomicU64::new(1);401 std::env::temp_dir().join(format!(402 "inf3r-verify-test-{}-{}.sock",403 std::process::id(),404 NEXT.fetch_add(1, Ordering::Relaxed)405 ))406 }407 408 fn serve_stub(listener: UnixListener) {409 serve_stub_with(listener, stub_catalogue());410 }411 412 fn serve_stub_with(listener: UnixListener, catalogue: Catalogue) {413 let (socket, _) = listener.accept().expect("the runner connects");414 loop {415 let Some((frame, _fds)) = recv_frame(&socket).expect("a frame") else {416 return;417 };418 if matches!(frame.header.kind, Kind::Extension(_)) {419 continue;420 }421 let body = Body::decode(frame.header.kind, &frame.payload).expect("a valid body");422 match body {423 Body::Hello(_) => {424 send(425 &socket,426 0,427 Kind::Welcome,428 &Body::Welcome(body::Welcome {429 v: 1,430 max_inflight: 1,431 }),432 );433 send(434 &socket,435 0,436 Kind::Catalogue,437 &Body::Catalogue(catalogue.clone()),438 );439 }440 Body::Grant(_) => send(441 &socket,442 0,443 Kind::Ready,444 &Body::Ready(body::Ready {445 load_ms: 0,446 cache_fingerprint: None,447 }),448 ),449 Body::Open(_) => send(450 &socket,451 frame.header.stream,452 Kind::Reject,453 &Body::Reject(body::Refusal {454 code: body::ErrorCode::Capability,455 detail: Some("not implemented by this binding".into()),456 }),457 ),458 Body::Bye(_) => return,459 _ => {}460 }461 }462 }463 464 fn serve_stub_refusing_load(listener: UnixListener) {465 let (socket, _) = listener.accept().expect("the runner connects");466 loop {467 let Some((frame, _fds)) = recv_frame(&socket).expect("a frame") else {468 return;469 };470 if matches!(frame.header.kind, Kind::Extension(_)) {471 continue;472 }473 let body = Body::decode(frame.header.kind, &frame.payload).expect("a valid body");474 match body {475 Body::Hello(_) => {476 send(477 &socket,478 0,479 Kind::Welcome,480 &Body::Welcome(body::Welcome {481 v: 1,482 max_inflight: 1,483 }),484 );485 send(486 &socket,487 0,488 Kind::Catalogue,489 &Body::Catalogue(stub_catalogue()),490 );491 }492 Body::Grant(_) => {493 send(494 &socket,495 0,496 Kind::Fatal,497 &Body::Fatal(body::Refusal {498 code: body::ErrorCode::Dependency,499 detail: Some("no room".into()),500 }),501 );502 return;503 }504 Body::Bye(_) => return,505 _ => {}506 }507 }508 }509 510 fn send(socket: &std::os::unix::net::UnixStream, stream: u16, kind: Kind, body: &Body) {511 let payload = body.encode();512 let length = u32::try_from(payload.len()).expect("a small body");513 send_frame(socket, Header::new(kind, stream, length), &payload, &[]).expect("send a frame");514 }515 516 fn stub_catalogue() -> Catalogue {517 stub_catalogue_with(Cancel::Token)518 }519 520 fn stub_catalogue_with(cancel: Cancel) -> Catalogue {521 Catalogue {522 target: Target {523 id: "stub".into(),524 backend: "stub".into(),525 arch: vec!["test".into()],526 devices: 0,527 vram_mb: Vec::new(),528 },529 models: vec![Model {530 serve: "stub".into(),531 alias_of: None,532 weights_bytes: 0,533 load_ms: 0,534 capabilities: BTreeMap::from([(535 "chat".into(),536 Capability {537 vocab: "chat.v1".into(),538 parts: vec![PartKind::Text],539 channels: vec!["text".into()],540 limits: BTreeMap::new(),541 cancel: cancel.clone(),542 stops: Stops::Plugin,543 queue: Queue::None,544 },545 )]),546 }],547 runtime: None,548 cache: None,549 }550 }