1 //! The operator client: one request per socket, one reply head and body.2 3 use std::io::{BufRead, BufReader, Read, Write};4 use std::net::TcpListener;5 use std::os::unix::fs::PermissionsExt;6 use std::os::unix::net::UnixListener;7 use std::path::{Path, PathBuf};8 use std::sync::atomic::{AtomicU64, Ordering};9 use std::thread;10 use std::time::{SystemTime, UNIX_EPOCH};11 12 use inf3r_cli::cli::{BundleVerb, Command, DEFAULT_SOCKET, engine_line, flatten, parse_args};13 use inf3r_cli::http::{CliError, Client};14 use inf3r_cli::new::{Bind, Shape, make_shape};15 use inf3r_json::parse;16 17 /// A path under the temporary directory. The counter keeps two tests in one18 /// process apart; the clock keeps two test processes apart.19 fn socket_path() -> PathBuf {20 static NEXT: AtomicU64 = AtomicU64::new(0);21 let n = NEXT.fetch_add(1, Ordering::Relaxed);22 let nanos = SystemTime::now()23 .duration_since(UNIX_EPOCH)24 .expect("a clock")25 .as_nanos();26 std::env::temp_dir().join(format!("inf3r-cli-{}-{nanos}-{n}.sock", std::process::id()))27 }28 29 /// Starts a server that accepts one connection, reads the request line, and30 /// writes a fixed reply.31 fn serve_once(response: &'static [u8]) -> PathBuf {32 serve_once_at("GET /jobs HTTP/1.1\r\n", response)33 }34 35 /// The same server, with the request line that it expects.36 fn serve_once_at(expected: &'static str, response: &'static [u8]) -> PathBuf {37 let path = socket_path();38 let listener = UnixListener::bind(&path).expect("bind a temporary socket");39 let served = path.clone();40 thread::spawn(move || {41 let (stream, _) = listener.accept().expect("accept");42 let mut reader = BufReader::new(stream.try_clone().expect("a file"));43 let mut request = String::new();44 reader45 .read_line(&mut request)46 .expect("read the request line");47 assert!(request.starts_with(expected), "{request}");48 let mut stream = stream;49 stream.write_all(response).expect("write the reply");50 stream.flush().expect("flush the reply");51 let _ = std::fs::remove_file(served);52 });53 path54 }55 56 #[test]57 fn a_fake_server_gives_the_status_and_the_body() {58 let path = serve_once(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");59 let reply = Client::new(path).get("/jobs").expect("a reply");60 assert_eq!(reply.status, 200);61 assert_eq!(reply.body, "ok");62 }63 64 #[test]65 fn a_body_shorter_than_its_length_is_short() {66 let path = serve_once(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nabc");67 let why = Client::new(path).get("/jobs").expect_err("a short body");68 assert!(matches!(why, CliError::Short { want: 5, got: 3 }), "{why}");69 }70 71 #[test]72 fn a_body_longer_than_its_length_is_short() {73 let path = serve_once(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nabcd");74 let why = Client::new(path).get("/jobs").expect_err("a long body");75 assert!(matches!(why, CliError::Short { want: 2, got: 4 }), "{why}");76 }77 78 #[test]79 fn a_chunked_reply_is_decoded() {80 let path = serve_once(81 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n",82 );83 let reply = Client::new(path).get("/jobs").expect("a chunked reply");84 assert_eq!(reply.status, 200);85 assert_eq!(reply.body, "abcde");86 }87 88 #[test]89 fn a_chunked_reply_with_a_trailer_ends_at_the_blank_line() {90 let path = serve_once(91 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ndata\r\n0\r\nX-Trace: 1\r\n\r\n",92 );93 let reply = Client::new(path).get("/jobs").expect("a chunked reply");94 assert_eq!(reply.body, "data");95 }96 97 #[test]98 fn a_chunk_size_that_is_not_hex_is_malformed() {99 let path =100 serve_once(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\nabc\r\n0\r\n\r\n");101 let why = Client::new(path).get("/jobs").expect_err("a bad chunk");102 assert!(matches!(why, CliError::Malformed(_)), "{why}");103 }104 105 #[test]106 fn a_refused_connection_names_the_path() {107 let path = socket_path();108 let why = Client::new(&path)109 .get("/jobs")110 .expect_err("no listener at the path");111 assert!(matches!(why, CliError::Connect { .. }), "{why}");112 assert!(113 why.to_string().contains(&path.display().to_string()),114 "{why}"115 );116 }117 118 #[test]119 fn flatten_joins_nested_keys_with_dots() {120 let value = parse(r#"{"a":{"b":1},"c":"x"}"#).expect("json");121 assert_eq!(flatten(&value), vec!["a.b=1", "c=x"]);122 }123 124 #[test]125 fn a_command_with_no_socket_uses_the_default() {126 let args = parse_args(vec!["ps".to_string()]).expect("a command");127 assert_eq!(args.socket, PathBuf::from(DEFAULT_SOCKET));128 assert_eq!(args.command, Command::Ps);129 }130 131 #[test]132 fn the_socket_option_overrides_the_default() {133 let args = parse_args(vec![134 "--socket".to_string(),135 "/x".to_string(),136 "ps".to_string(),137 ])138 .expect("a command");139 assert_eq!(args.socket, PathBuf::from("/x"));140 assert_eq!(args.command, Command::Ps);141 }142 143 #[test]144 fn a_socket_option_without_a_path_is_a_usage_error() {145 let why = parse_args(vec!["--socket".to_string()]).expect_err("no path");146 assert!(matches!(why, CliError::Usage(_)), "{why}");147 }148 149 #[test]150 fn the_request_reaches_the_server_before_the_reply_is_read() {151 // The fake server asserts the request line in its thread. Reading the reply152 // here proves that the write and the read use one connection.153 let path = serve_once(b"HTTP/1.1 404 Not Found\r\nContent-Length: 4\r\n\r\nnope");154 let reply = Client::new(path).get("/jobs").expect("a reply");155 assert_eq!(reply.status, 404);156 assert_eq!(reply.body, "nope");157 }158 159 #[test]160 fn a_reader_that_ends_early_is_not_a_reply() {161 let path = serve_once(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n");162 // No blank line, so the reply head never ends.163 let why = Client::new(path).get("/jobs").expect_err("no head end");164 assert!(matches!(why, CliError::Malformed(_)), "{why}");165 }166 167 #[test]168 fn verify_takes_a_plugin_id_from_the_deploy_file() {169 let args =170 parse_args(vec!["verify".to_string(), "mock/x64-cpu".to_string()]).expect("a command");171 match args.command {172 Command::Verify(verify) => {173 assert_eq!(verify.plugin.as_deref(), Some("mock/x64-cpu"));174 assert_eq!(verify.program, None);175 assert!(verify.program_args.is_empty());176 assert_eq!(verify.deploy, PathBuf::from("deploy.toml"));177 }178 other => panic!("{other:?}"),179 }180 }181 182 #[test]183 fn verify_takes_a_weight_file() {184 let args = parse_args(vec![185 "verify".to_string(),186 "mock/x64-cpu".to_string(),187 "--weights".to_string(),188 "model.gguf".to_string(),189 ])190 .expect("a command");191 match args.command {192 Command::Verify(verify) => {193 assert_eq!(verify.weights, Some(PathBuf::from("model.gguf")));194 }195 other => panic!("{other:?}"),196 }197 }198 199 #[test]200 fn verify_takes_a_program_and_its_words() {201 let args = parse_args(vec![202 "verify".to_string(),203 "--program".to_string(),204 "python3".to_string(),205 "--".to_string(),206 "plugin.py".to_string(),207 "--socket".to_string(),208 ])209 .expect("a command");210 match args.command {211 Command::Verify(verify) => {212 assert_eq!(verify.plugin, None);213 assert_eq!(verify.program, Some(PathBuf::from("python3")));214 assert_eq!(verify.program_args, vec!["plugin.py", "--socket"]);215 }216 other => panic!("{other:?}"),217 }218 }219 220 #[test]221 fn verify_takes_a_budget_a_load_budget_a_job_budget_and_a_suite() {222 let args = parse_args(vec![223 "verify".to_string(),224 "mock/x64-cpu".to_string(),225 "--budget".to_string(),226 "10m".to_string(),227 "--load-budget".to_string(),228 "90s".to_string(),229 "--job-budget".to_string(),230 "2500ms".to_string(),231 "--suite".to_string(),232 "goldens/jobs.json".to_string(),233 ])234 .expect("a command");235 match args.command {236 Command::Verify(verify) => {237 assert_eq!(verify.budget, Some(std::time::Duration::from_secs(600)));238 assert_eq!(verify.load_budget, Some(std::time::Duration::from_secs(90)));239 assert_eq!(240 verify.job_budget,241 Some(std::time::Duration::from_millis(2_500))242 );243 assert_eq!(verify.suite, Some(PathBuf::from("goldens/jobs.json")));244 }245 other => panic!("{other:?}"),246 }247 }248 249 #[test]250 fn verify_takes_a_container_mode_and_a_private_socket_root() {251 let args = parse_args(vec![252 "verify".to_string(),253 "mock/x64-cpu".to_string(),254 "--container".to_string(),255 "--image".to_string(),256 "inf3r/mock/x64-cpu:sha-0123456789ab".to_string(),257 "--socket-dir".to_string(),258 "/tmp/ifg".to_string(),259 "--socket-host-dir".to_string(),260 "/tmp/ifg-host".to_string(),261 "--deploy".to_string(),262 "docker/config/gate.toml".to_string(),263 ])264 .expect("a command");265 match args.command {266 Command::Verify(verify) => {267 assert!(verify.container);268 assert_eq!(269 verify.image.as_deref(),270 Some("inf3r/mock/x64-cpu:sha-0123456789ab")271 );272 assert_eq!(verify.socket_dir, Some(PathBuf::from("/tmp/ifg")));273 assert_eq!(verify.socket_host_dir, Some(PathBuf::from("/tmp/ifg-host")));274 assert_eq!(verify.deploy, PathBuf::from("docker/config/gate.toml"));275 }276 other => panic!("{other:?}"),277 }278 let why = parse_args(vec![279 "verify".to_string(),280 "mock/x64-cpu".to_string(),281 "--image".to_string(),282 "inf3r/mock/x64-cpu:sha-0123456789ab".to_string(),283 ])284 .expect_err("an image belongs to container mode");285 assert!(matches!(why, CliError::Usage(_)), "{why}");286 let why = parse_args(vec![287 "verify".to_string(),288 "mock/x64-cpu".to_string(),289 "--container".to_string(),290 "--image".to_string(),291 "inf3r/mock/x64-cpu:latest".to_string(),292 ])293 .expect_err("a latest image is not a pin");294 assert!(matches!(why, CliError::Usage(_)), "{why}");295 let why = parse_args(vec![296 "verify".to_string(),297 "mock/x64-cpu".to_string(),298 "--container".to_string(),299 "--program".to_string(),300 "target/debug/inf3r-mock-x64-cpu".to_string(),301 ])302 .expect_err("a container does not take a host program");303 assert!(matches!(why, CliError::Usage(_)), "{why}");304 }305 306 #[test]307 fn a_budget_belongs_only_to_verify() {308 let why = parse_args(vec![309 "ps".to_string(),310 "--budget".to_string(),311 "1m".to_string(),312 ])313 .expect_err("a rejected option");314 assert!(matches!(why, CliError::Usage(_)), "{why}");315 }316 317 #[test]318 fn verify_needs_a_plugin_or_a_program() {319 let why = parse_args(vec!["verify".to_string()]).expect_err("no target");320 assert!(matches!(why, CliError::Usage(_)), "{why}");321 }322 323 #[test]324 fn container_verify_reports_deploy_conflicts_before_docker() {325 let dir = std::env::temp_dir().join(format!("inf3r-cli-conflict-{}", std::process::id()));326 let _ = std::fs::remove_dir_all(&dir);327 std::fs::create_dir_all(&dir).expect("a test directory");328 std::fs::write(dir.join("token"), format!("{}\n", "a".repeat(64))).expect("token");329 let deploy = dir.join("deploy.toml");330 std::fs::write(331 &deploy,332 format!(333 "[[node]]\nhost = \"test\"\nbin_dir = \"bin\"\nbundle_dirs = [\"{}\"]\nblob_dir = \"{}\"\nsocket_dir = \"{}\"\nweb = {{ unix = \"{}\" }}\nauth_file = \"{}\"\n\n[[node.bind]]\nbundle = \"mock/x64-cpu\"\nruntime = \"container\"\nimage = \"inf3r/example:1\"\nmodels = [\"mock\"]\ndevices = [\"cpu:0\"]\n",334 dir.join("plugins").display(),335 dir.join("blobs").display(),336 dir.join("sockets").display(),337 dir.join("web.sock").display(),338 dir.join("token").display()339 ),340 )341 .expect("deploy");342 let output = std::process::Command::new(env!("CARGO_BIN_EXE_inf3r"))343 .args([344 "verify",345 "--container",346 "--deploy",347 deploy.to_str().unwrap(),348 "mock/x64-cpu",349 ])350 .output()351 .expect("run the cli");352 let stderr = String::from_utf8_lossy(&output.stderr);353 assert!(!output.status.success(), "{stderr}");354 assert!(stderr.contains("deploy conflict"), "{stderr}");355 assert!(stderr.contains("probe_image"), "{stderr}");356 let _ = std::fs::remove_dir_all(&dir);357 }358 359 #[test]360 fn doctor_takes_a_deploy_file() {361 let args = parse_args(vec![362 "doctor".to_string(),363 "--deploy".to_string(),364 "packages/deploy.toml".to_string(),365 ])366 .expect("a command");367 match args.command {368 Command::Doctor(doctor) => {369 assert_eq!(doctor.deploy, PathBuf::from("packages/deploy.toml"));370 }371 other => panic!("{other:?}"),372 }373 }374 375 #[test]376 fn doctor_checks_the_profile_the_token_and_the_blob_store() {377 let root = bundle_dir("doctor-pass");378 let bundle = root.join("plugins/tiny/x64-cpu");379 std::fs::create_dir_all(&bundle).expect("a bundle tree");380 std::fs::write(381 bundle.join("target.toml"),382 format!(383 "[target]\nname = \"x64-cpu\"\nbackend = \"cpu\"\narch = [\"{}\"]\ndevices = 0\nvram_mb = []\n",384 std::env::consts::ARCH385 ),386 )387 .expect("a target profile");388 let token = root.join("token");389 std::fs::write(&token, format!("{}\n", "a".repeat(64))).expect("a token");390 let blobs = root.join("blobs");391 std::fs::create_dir_all(&blobs).expect("a blob store");392 let cache = root.join("cache");393 std::fs::create_dir_all(&cache).expect("a cache tier");394 use std::os::unix::fs::PermissionsExt;395 std::fs::set_permissions(&cache, std::fs::Permissions::from_mode(0o700))396 .expect("a private cache tier");397 let deploy = root.join("deploy.toml");398 std::fs::write(399 &deploy,400 format!(401 "[[node]]\nhost = \"test\"\nbin_dir = \"bin\"\nbundle_dirs = [\"{}\"]\nblob_dir = \"{}\"\nweb = {{ unix = \"/tmp/inf3r-doctor.sock\" }}\nauth_file = \"{}\"\n[node.cache]\nenabled = true\n[[node.cache.tier]]\nname = \"nvme\"\ndir = \"{}\"\nbound = \"64MB\"\n[[node.bind]]\nbundle = \"tiny/x64-cpu\"\nmodels = [\"tiny\"]\ndevices = [\"cpu:0\"]\n",402 root.join("plugins").display(),403 blobs.display(),404 token.display(),405 cache.display()406 ),407 )408 .expect("a deploy file");409 let check = inf3r_cli::doctor::checks(&deploy).expect("the deploy checks");410 assert!(check.ok, "{:?}", check.lines);411 assert!(412 check413 .lines414 .iter()415 .any(|line| line == "profile tiny/x64-cpu: ok"),416 "{:?}",417 check.lines418 );419 assert!(420 check.lines.iter().any(|line| line.starts_with("token ")),421 "{:?}",422 check.lines423 );424 assert!(425 check.lines.iter().any(|line| line.starts_with("blobs ")),426 "{:?}",427 check.lines428 );429 assert!(430 check431 .lines432 .iter()433 .any(|line| line.starts_with("cache tier nvme: ok")),434 "{:?}",435 check.lines436 );437 let _ = std::fs::remove_dir_all(&root);438 }439 440 /// A directory under the temporary directory for a bundle test.441 fn bundle_dir(name: &str) -> PathBuf {442 static NEXT: AtomicU64 = AtomicU64::new(0);443 let n = NEXT.fetch_add(1, Ordering::Relaxed);444 let base = std::env::var_os("CARGO_TARGET_TMPDIR")445 .map(PathBuf::from)446 .unwrap_or_else(std::env::temp_dir);447 let dir = base.join(format!(448 "inf3r-cli-bundle-{}-{name}-{n}",449 std::process::id()450 ));451 let _ = std::fs::remove_dir_all(&dir);452 std::fs::create_dir_all(&dir).expect("a temporary directory");453 dir454 }455 456 #[test]457 fn a_tampered_bundle_fails_the_bundle_check() {458 let root = bundle_dir("tampered");459 let bundle = root.join("plugins/mock/x64-cpu");460 std::fs::create_dir_all(bundle.join("models")).expect("a bundle tree");461 std::fs::create_dir_all(bundle.join("model")).expect("a weights directory");462 std::fs::create_dir_all(bundle.join("engine")).expect("an engine directory");463 std::fs::write(bundle.join("BUNDLE.md"), b"# the bundle\n").expect("a card");464 std::fs::write(bundle.join("inf3r-mock-x64-cpu"), b"the binary").expect("a binary");465 std::fs::write(bundle.join("target.toml"), b"[target]\n").expect("a target");466 std::fs::write(bundle.join("models/mock.toml"), b"[model]\n").expect("a model");467 let manifest = |sha: &str| {468 format!(469 "id = \"mock/x64-cpu\"\nmodel = \"mock\"\ntarget = \"x64-cpu\"\nsummary = \"the conformance bundle\"\nengine = \"authored\"\nbinary = \"inf3r-mock-x64-cpu\"\nfiles = \"target.toml,models/mock.toml,BUNDLE.md\"\nsha256 = \"{sha}\"\n"470 )471 };472 std::fs::write(bundle.join("bundle.toml"), manifest(&"0".repeat(64))).expect("a manifest");473 let digest = inf3r_bundle::Bundle::digest(&bundle).expect("a digest");474 std::fs::write(bundle.join("bundle.toml"), manifest(&digest)).expect("a manifest");475 let deploy = root.join("deploy.toml");476 std::fs::write(477 &deploy,478 format!(479 "[[node]]\nhost = \"test\"\nbin_dir = \"bin\"\nbundle_dirs = [\"{}\"]\nblob_dir = \"blobs\"\nweb = {{ unix = \"/tmp/inf3r-test.sock\" }}\nauth_file = \"token\"\n",480 root.join("plugins").display()481 ),482 )483 .expect("a deploy file");484 485 let good = inf3r_cli::bundle::bundles(&deploy).expect("the bundle check");486 assert!(good.ok);487 assert_eq!(good.lines, vec!["bundle mock/x64-cpu: ok"]);488 489 std::fs::write(bundle.join("target.toml"), b"[target]\nchanged\n").expect("a changed file");490 let bad = inf3r_cli::bundle::bundles(&deploy).expect("the bundle check");491 assert!(!bad.ok);492 assert_eq!(bad.lines.len(), 1);493 assert!(494 bad.lines[0].starts_with("bundle mock/x64-cpu: "),495 "{:?}",496 bad.lines497 );498 assert!(bad.lines[0].contains("digest"), "{:?}", bad.lines);499 500 let status = std::process::Command::new(env!("CARGO_BIN_EXE_inf3r"))501 .args(["doctor", "--deploy"])502 .arg(&deploy)503 .status()504 .expect("the doctor command");505 assert_eq!(status.code(), Some(1));506 }507 508 #[test]509 fn a_tcp_client_sends_the_bearer_token() {510 let listener = TcpListener::bind("127.0.0.1:0").expect("a TCP listener");511 let address = listener.local_addr().expect("an address");512 thread::spawn(move || {513 let (mut stream, _) = listener.accept().expect("accept");514 let mut head = [0u8; 1024];515 let n = stream.read(&mut head).expect("the request");516 let text = String::from_utf8_lossy(&head[..n]);517 assert!(text.starts_with("GET /jobs HTTP/1.1\r\n"), "{text}");518 assert!(519 text.contains("authorization: Bearer abc\r\n")520 || text.contains("Authorization: Bearer abc\r\n"),521 "{text}"522 );523 stream524 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")525 .expect("the reply");526 });527 let reply = Client::tcp(address.to_string())528 .with_token(Some("abc".to_string()))529 .get("/jobs")530 .expect("a reply");531 assert_eq!(reply.body, "ok");532 }533 534 #[test]535 fn ps_reads_stats_and_names_the_bundle_and_the_device() {536 let body = r#"{"engines":[{"plugin":"mock/x64-cpu","served":["mock"],"slots":1,"in_flight":0,"queued":0,"declared_bytes":0,"load_ms":1,"measured_bytes":0,"tokens_per_s":1234}],"peers":[{"model":"mock","plugin":"mock/x64-cpu","in_flight":0}],"devices":[{"device":"cuda:0","bytes":100,"used":1}],"blobs":{"bytes":2,"limit":3}}"#;537 let reply = Box::leak(538 format!(539 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",540 body.len(),541 body542 )543 .into_boxed_str(),544 )545 .as_bytes();546 let path = serve_once_at("GET /stats HTTP/1.1\r\n", reply);547 let output = run_inf3r(&["--socket", &path.display().to_string(), "ps"]);548 assert!(output.status.success(), "{output:?}");549 let text = String::from_utf8_lossy(&output.stdout);550 assert!(text.contains("bundle mock/x64-cpu"), "{text}");551 assert!(text.contains("tok/s=12.34"), "{text}");552 assert!(text.contains("device cuda:0"), "{text}");553 assert!(text.contains("model mock"), "{text}");554 assert!(text.contains("blobs bytes=2 limit=3"), "{text}");555 }556 557 #[test]558 fn ps_json_is_one_object() {559 let body = r#"{"engines":[],"peers":[],"devices":[],"blobs":{"bytes":0,"limit":0}}"#;560 let reply = Box::leak(561 format!(562 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",563 body.len(),564 body565 )566 .into_boxed_str(),567 )568 .as_bytes();569 let path = serve_once_at("GET /stats HTTP/1.1\r\n", reply);570 let output = run_inf3r(&["--socket", &path.display().to_string(), "--json", "ps"]);571 assert!(output.status.success(), "{output:?}");572 let text = String::from_utf8(output.stdout).expect("UTF-8");573 let root = parse(&text).expect("one JSON object");574 assert!(root.get("engines").is_some(), "{text}");575 }576 577 #[test]578 fn reload_posts_the_bundle_and_prints_the_reply() {579 const BODY: &str = r#"{"reloaded":[{"bundle":"mock/x64-cpu"}],"failed":[]}"#;580 let reply = Box::leak(581 format!(582 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",583 BODY.len(),584 BODY585 )586 .into_boxed_str(),587 )588 .as_bytes();589 let path = serve_once_at("POST /reload HTTP/1.1\r\n", reply);590 let output = run_inf3r(&[591 "--socket",592 &path.display().to_string(),593 "reload",594 "mock/x64-cpu",595 ]);596 assert!(output.status.success(), "{output:?}");597 assert!(598 String::from_utf8_lossy(&output.stdout).contains("reloaded mock/x64-cpu"),599 "{}",600 String::from_utf8_lossy(&output.stdout)601 );602 }603 604 #[test]605 fn an_engine_line_prints_a_dash_for_a_missing_number_and_the_number_otherwise() {606 let value = parse(607 r#"{"plugin":"echo","slots":1,"in_flight":0,"queued":2,"declared_bytes":4096,"tokens_per_s":123}"#,608 )609 .expect("json");610 assert_eq!(611 engine_line(&value).expect("a line"),612 "engine echo slots=1 inflight=0 queued=2 load_ms=- declared=4096 measured=- tok/s=1.23"613 );614 }615 616 #[test]617 fn json_is_one_global_switch() {618 let args = parse_args(["ps", "--json"].map(String::from)).expect("a command");619 assert!(args.json);620 assert_eq!(args.command, Command::Ps);621 let args = parse_args(["--json", "ps"].map(String::from)).expect("a command");622 assert!(args.json);623 }624 625 #[test]626 fn tcp_and_token_are_the_remote_client_options() {627 let args =628 parse_args(["--tcp", "127.0.0.1:8080", "--token-file", "token", "ps"].map(String::from))629 .expect("a command");630 assert_eq!(args.tcp.as_deref(), Some("127.0.0.1:8080"));631 assert_eq!(args.token_file, Some(PathBuf::from("token")));632 let why = parse_args(["--socket", "/tmp/x", "--tcp", "127.0.0.1:8080", "ps"].map(String::from))633 .expect_err("two endpoints");634 assert!(matches!(why, CliError::Usage(_)), "{why}");635 let why = parse_args(["--token", "a", "--token-file", "b", "ps"].map(String::from))636 .expect_err("two tokens");637 assert!(matches!(why, CliError::Usage(_)), "{why}");638 }639 640 #[test]641 fn reload_takes_zero_or_one_bundle() {642 let args = parse_args(["reload"].map(String::from)).expect("a reload");643 assert_eq!(644 args.command,645 Command::Reload(inf3r_cli::ReloadArgs { bundle: None })646 );647 let args = parse_args(["reload", "mock/x64-cpu"].map(String::from)).expect("a reload");648 assert_eq!(649 args.command,650 Command::Reload(inf3r_cli::ReloadArgs {651 bundle: Some("mock/x64-cpu".to_string())652 })653 );654 let why = parse_args(["reload", "a", "b"].map(String::from)).expect_err("too many");655 assert!(matches!(why, CliError::Usage(_)), "{why}");656 }657 658 #[test]659 fn bundle_verify_and_seal_are_one_command_with_two_verbs() {660 let args = parse_args(["bundle", "verify", "plugins/mock/x64-cpu"].map(String::from))661 .expect("a verify command");662 match args.command {663 Command::Bundle(bundle) => {664 assert_eq!(bundle.verb, BundleVerb::Verify);665 assert_eq!(bundle.dir, PathBuf::from("plugins/mock/x64-cpu"));666 }667 other => panic!("{other:?}"),668 }669 let args = parse_args(["bundle", "seal", "plugins/mock/x64-cpu"].map(String::from))670 .expect("a seal command");671 match args.command {672 Command::Bundle(bundle) => assert_eq!(bundle.verb, BundleVerb::Seal),673 other => panic!("{other:?}"),674 }675 let why = parse_args(["bundle", "paint", "plugins/mock/x64-cpu"].map(String::from))676 .expect_err("an unknown verb");677 assert!(matches!(why, CliError::Usage(_)), "{why}");678 let why = parse_args(["bundle", "verify"].map(String::from)).expect_err("no directory");679 assert!(matches!(why, CliError::Usage(_)), "{why}");680 }681 682 fn run_inf3r(words: &[&str]) -> std::process::Output {683 std::process::Command::new(env!("CARGO_BIN_EXE_inf3r"))684 .args(words)685 .output()686 .expect("the inf3r command")687 }688 689 fn run_inf3r_in(dir: &Path, words: &[&str]) -> std::process::Output {690 std::process::Command::new(env!("CARGO_BIN_EXE_inf3r"))691 .current_dir(dir)692 .args(words)693 .output()694 .expect("the inf3r command")695 }696 697 #[test]698 fn every_shape_writes_the_five_bundle_parts() {699 for shape in [700 Shape::Default,701 Shape::Engine,702 Shape::Bind(Bind::Binary),703 Shape::Bind(Bind::Http),704 Shape::Library,705 ] {706 let root = bundle_dir("parts");707 let dir = make_shape(&root, "tiny", "cpu-x", "chat", shape).expect("a bundle");708 for relative in [709 "bundle.toml",710 "BUNDLE.md",711 "target.toml",712 "models/tiny.toml",713 "model/.gitignore",714 "model/.gitkeep",715 "engine/README.md",716 "goldens/.gitkeep",717 "src/main.rs",718 "Cargo.toml",719 "tests/tiny.rs",720 "inf3r-tiny-cpu-x",721 ] {722 assert!(dir.join(relative).is_file(), "{shape:?}: {relative}");723 }724 let card = std::fs::read_to_string(dir.join("BUNDLE.md")).expect("the card");725 assert!(card.starts_with("# tiny/cpu-x\n"), "{card}");726 for line in ["model: tiny", "target: cpu-x", "engine:", "run:"] {727 assert!(card.contains(line), "{card}");728 }729 let ignore = std::fs::read_to_string(dir.join("model/.gitignore")).expect("the ignore");730 assert_eq!(ignore, "*\n!.gitignore\n!.gitkeep\n");731 let launcher = std::fs::metadata(dir.join("inf3r-tiny-cpu-x")).expect("the launcher");732 assert_eq!(launcher.permissions().mode() & 0o777, 0o755);733 let _ = std::fs::remove_dir_all(&root);734 }735 }736 737 #[test]738 fn every_bound_bundle_calls_the_binder_with_its_own_manifest_dir() {739 for bind in [Bind::Binary, Bind::Http] {740 let root = bundle_dir("bind-main");741 let dir = make_shape(&root, "tiny", "cpu-x", "chat", Shape::Bind(bind)).expect("a bundle");742 let main = std::fs::read_to_string(dir.join("src/main.rs")).expect("the entry point");743 assert_eq!(744 main,745 "fn main() -> std::process::ExitCode { inf3r_bind::main_at(env!(\"CARGO_MANIFEST_DIR\")) }\n"746 );747 let _ = std::fs::remove_dir_all(&root);748 }749 let root = bundle_dir("bind-main-library");750 let dir = make_shape(&root, "tiny", "cpu-x", "chat", Shape::Library).expect("a bundle");751 let main = std::fs::read_to_string(dir.join("src/main.rs")).expect("the entry point");752 assert!(!main.contains("inf3r_bind"), "{main}");753 assert!(main.contains("mod ffi;"), "{main}");754 assert!(dir.join("src/ffi.rs").is_file());755 assert!(dir.join("engine/engine.c").is_file());756 let _ = std::fs::remove_dir_all(&root);757 }758 759 #[test]760 fn generated_default_engine_and_binary_bundles_verify() {761 for shape in [762 Shape::Default,763 Shape::Engine,764 Shape::Bind(Bind::Binary),765 Shape::Library,766 ] {767 let root = bundle_dir("verify-generated");768 let dir = make_shape(&root, "tiny", "cpu-x", "chat", shape).expect("a bundle");769 let output = run_inf3r(&["bundle", "verify", &dir.display().to_string()]);770 assert!(771 output.status.success(),772 "{shape:?}: {}",773 String::from_utf8_lossy(&output.stdout)774 );775 assert!(776 String::from_utf8_lossy(&output.stdout).contains("bundle tiny/cpu-x: ok"),777 "{shape:?}: {}",778 String::from_utf8_lossy(&output.stdout)779 );780 let _ = std::fs::remove_dir_all(&root);781 }782 }783 784 /// Builds a generated bundle in its own target directory and returns the785 /// plugin binary. The bundle's build script compiles `engine/engine.c`.786 fn build_generated(dir: &Path, model: &str, target: &str) -> PathBuf {787 let target_dir = dir.join("target");788 let status = std::process::Command::new(env!("CARGO"))789 .args(["build", "--offline", "--manifest-path"])790 .arg(dir.join("Cargo.toml"))791 .env("CARGO_TARGET_DIR", &target_dir)792 .status()793 .expect("cargo build");794 assert!(status.success(), "the generated bundle did not build");795 let status = std::process::Command::new(env!("CARGO"))796 .args(["test", "--offline", "--manifest-path"])797 .arg(dir.join("Cargo.toml"))798 .env("CARGO_TARGET_DIR", &target_dir)799 .status()800 .expect("cargo test");801 assert!(status.success(), "the generated bundle tests did not pass");802 target_dir803 .join("debug")804 .join(format!("inf3r-{model}-{target}"))805 }806 807 #[test]808 fn a_generated_library_bundle_builds_and_passes_the_gate() {809 let root = bundle_dir("library-build");810 // The generated workspace reaches the engine crates at `<root>/crates`.811 // A temporary root gets that path as a link to this checkout.812 let crates = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../crates");813 std::os::unix::fs::symlink(crates, root.join("crates")).expect("a crates link");814 let created = run_inf3r_in(&root, &["new", "foo", "cpu", "chat", "--bind", "library"]);815 assert!(816 created.status.success(),817 "{}",818 String::from_utf8_lossy(&created.stdout)819 );820 let dir = root.join("plugins").join("foo").join("cpu");821 let verified = run_inf3r(&["bundle", "verify", &dir.display().to_string()]);822 assert!(823 verified.status.success(),824 "{}",825 String::from_utf8_lossy(&verified.stdout)826 );827 828 let binary = build_generated(&dir, "foo", "cpu");829 let verified_again = run_inf3r(&["bundle", "verify", &dir.display().to_string()]);830 assert!(831 verified_again.status.success(),832 "{}",833 String::from_utf8_lossy(&verified_again.stdout)834 );835 let output = run_inf3r(&["verify", "--program", &binary.display().to_string()]);836 assert!(837 output.status.success(),838 "{}",839 String::from_utf8_lossy(&output.stdout)840 );841 let stdout = String::from_utf8_lossy(&output.stdout);842 assert!(stdout.contains("pass chat"), "{stdout}");843 let _ = std::fs::remove_dir_all(&root);844 }845 846 #[test]847 fn a_byte_change_fails_until_the_bundle_is_resealed() {848 let root = bundle_dir("seal-after-change");849 let dir = make_shape(&root, "tiny", "cpu-x", "chat", Shape::Default).expect("a bundle");850 let path = dir.display().to_string();851 std::fs::write(dir.join("target.toml"), b"[target]\nchanged\n").expect("a changed file");852 let failed = run_inf3r(&["bundle", "verify", &path]);853 assert_eq!(failed.status.code(), Some(1));854 assert!(855 String::from_utf8_lossy(&failed.stdout).contains("digest"),856 "{}",857 String::from_utf8_lossy(&failed.stdout)858 );859 860 let sealed = run_inf3r(&["bundle", "seal", &path]);861 assert!(sealed.status.success());862 let digest = String::from_utf8_lossy(&sealed.stdout).trim().to_string();863 assert_eq!(digest.len(), 64, "{digest}");864 865 let passed = run_inf3r(&["bundle", "verify", &path]);866 assert!(passed.status.success());867 assert!(868 String::from_utf8_lossy(&passed.stdout).contains("bundle tiny/cpu-x: ok"),869 "{}",870 String::from_utf8_lossy(&passed.stdout)871 );872 let _ = std::fs::remove_dir_all(&root);873 }874 875 #[test]876 fn a_bound_new_with_embed_is_a_usage_error() {877 let why = parse_args(["new", "tiny", "cpu-x", "embed", "--bind", "binary"].map(String::from))878 .expect_err("the binder serves chat only");879 assert!(matches!(why, CliError::Usage(_)), "{why}");880 assert!(why.to_string().contains("chat"), "{why}");881 }882 883 #[test]884 fn a_library_new_is_an_ffi_bundle_not_the_binder() {885 let args = parse_args(["new", "foo", "cpu", "chat", "--bind", "library"].map(String::from))886 .expect("a library command");887 match args.command {888 Command::New(new) => assert_eq!(new.shape, Shape::Library),889 other => panic!("{other:?}"),890 }891 let args = parse_args(["new", "foo", "cpu", "embed", "--bind", "library"].map(String::from))892 .expect("a library bundle is not limited to the binder's chat");893 match args.command {894 Command::New(new) => assert_eq!(new.shape, Shape::Library),895 other => panic!("{other:?}"),896 }897 }