1 //! The toy plugin as a process, over the wire that the core speaks.2 //!3 //! Every test writes its own GGUF file, starts the binary on a private4 //! filesystem socket, loads the file through a grant, and reads a real job.5 use inf3r_proto::Value;6 use inf3r_proto::body::{self, Grant, Open, PartKind};7 use inf3r_proto::client::{Item, Job, Peer};8 use std::fs;9 use std::fs::File;10 use std::os::fd::AsFd;11 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};12 use std::os::unix::net::UnixListener;13 use std::path::{Path, PathBuf};14 use std::process::{Child, Command, Stdio};15 use std::sync::atomic::{AtomicU64, Ordering};16 use std::time::Duration;17 const WAIT: Duration = Duration::from_secs(10);18 const BIN: &str = env!("CARGO_BIN_EXE_inf3r-toy-x64-cpu");19 /// The token count of a job that runs to the decoder's ceiling.20 const TOKENS: usize = 8;21 /// Enough credit for any job here. The cancel test uses one byte instead.22 const CREDIT: u64 = 1 << 20;23 /// A unique number for a temporary file or a private socket directory.24 fn next() -> u64 {25 static NEXT: AtomicU64 = AtomicU64::new(0);26 NEXT.fetch_add(1, Ordering::Relaxed)27 }28 fn push_str(out: &mut Vec<u8>, text: &str) {29 out.extend_from_slice(&(text.len() as u64).to_le_bytes());30 out.extend_from_slice(text.as_bytes());31 }32 /// Builds a whole GGUF file by hand.33 ///34 /// The embedding rows select token 1 from any history whose newest id is 1:35 /// row 1 is `[1, 0, ...]` and every other row is zero. The prompt `A` has the36 /// byte 65, which is id 1 modulo a two-token vocabulary.37 fn build(vocab: &[&str], stop: &str) -> Vec<u8> {38 const ALIGN: usize = 32;39 const WIDTH: usize = 8;40 let mut out = Vec::new();41 out.extend_from_slice(b"GGUF");42 out.extend_from_slice(&3u32.to_le_bytes());43 out.extend_from_slice(&1u64.to_le_bytes());44 out.extend_from_slice(&2u64.to_le_bytes());45 push_str(&mut out, "toy.vocab");46 out.extend_from_slice(&12u32.to_le_bytes());47 out.extend_from_slice(&11u32.to_le_bytes());48 out.extend_from_slice(&(vocab.len() as u64).to_le_bytes());49 for token in vocab {50 push_str(&mut out, token);51 }52 push_str(&mut out, "toy.stop");53 out.extend_from_slice(&11u32.to_le_bytes());54 push_str(&mut out, stop);55 push_str(&mut out, "embed");56 out.extend_from_slice(&2u32.to_le_bytes());57 out.extend_from_slice(&(vocab.len() as u64).to_le_bytes());58 out.extend_from_slice(&(WIDTH as u64).to_le_bytes());59 out.extend_from_slice(&0u32.to_le_bytes());60 out.extend_from_slice(&0u64.to_le_bytes());61 let rem = out.len() % ALIGN;62 if rem != 0 {63 out.resize(out.len() + (ALIGN - rem), 0);64 }65 for token in 0..vocab.len() {66 for position in 0..WIDTH {67 let value = if token == 1 && position == 0 {68 1.0f3269 } else {70 0.0f3271 };72 out.extend_from_slice(&value.to_le_bytes());73 }74 }75 out76 }77 /// Writes a generated model to a fresh path under the temporary directory.78 fn weights(vocab: &[&str], stop: &str) -> PathBuf {79 let path =80 std::env::temp_dir().join(format!("inf3r-toy-{}-{}.gguf", std::process::id(), next()));81 fs::write(&path, build(vocab, stop)).expect("write the generated GGUF");82 path83 }84 /// The grant that hands the descriptor to the plugin. The path is empty so the85 /// load has no second source for the bytes.86 fn grant(len: u64) -> Grant {87 Grant {88 deps: vec![body::Dependency {89 role: "weights".into(),90 fd: 0,91 len,92 path: String::new(),93 }],94 }95 }96 /// A private socket directory that is removed when the test ends.97 struct SocketDir(PathBuf);98 99 impl Drop for SocketDir {100 fn drop(&mut self) {101 let _ = fs::remove_dir_all(&self.0);102 }103 }104 105 /// Starts the binary on a private socket and loads the file.106 fn start(path: &Path) -> (Peer, Child, SocketDir) {107 let dir = Path::new("/tmp").join(format!("inf3r-toy-{}-{}", std::process::id(), next()));108 fs::DirBuilder::new()109 .mode(0o700)110 .create(&dir)111 .expect("the private directory");112 let dir = SocketDir(dir);113 let socket = dir.0.join("socket");114 let listener = UnixListener::bind(&socket).expect("bind");115 let child = Command::new(BIN)116 .arg("--socket")117 .arg(&socket)118 .stdout(Stdio::null())119 .stderr(Stdio::null())120 .spawn()121 .expect("spawn the plugin");122 let (stream, _) = listener.accept().expect("the plugin connects");123 let peer = Peer::connect(stream, "toy-test", WAIT).expect("handshake");124 // The descriptor is the only way the bytes arrive; the plugin reads it125 // through `/proc/self/fd`, the same path as a real load.126 let file = File::open(path).expect("open the weight file");127 let len = file.metadata().expect("the file exists").len();128 peer.load_fds(&grant(len), &[file.as_fd()], WAIT)129 .unwrap_or_else(|why| panic!("load: {why}"));130 (peer, child, dir)131 }132 133 /// One chat whose only part is the prompt `A`.134 fn open(credit: u64) -> Open {135 Open {136 request_id: "r-1".into(),137 model: "toy".into(),138 capability: "chat".into(),139 credit,140 budget_ms: 10_000,141 parts: vec![body::Part {142 kind: PartKind::Text,143 mime: "text/plain; charset=utf-8".into(),144 role: None,145 len: 1,146 hold: body::Hold::Inline(b"A".to_vec()),147 }],148 params: Value::Map(Vec::new()),149 }150 }151 /// Reads every event and returns them with the terminal frame.152 fn drain(job: &mut Job) -> (Vec<String>, body::Done) {153 let mut chunks = Vec::new();154 loop {155 match job.next().expect("read").expect("an item") {156 Item::Accepted(_) => {}157 Item::Event { data, .. } => {158 chunks.push(String::from_utf8(data).expect("the toy emits UTF-8"));159 }160 Item::Done(done, _) => return (chunks, done),161 Item::Reject(refusal) => panic!("refused: {refusal:?}"),162 }163 }164 }165 /// Runs one job to its terminal frame.166 fn run(path: &Path, credit: u64) -> (Vec<String>, body::Done, Peer, Child, SocketDir) {167 let (peer, child, dir) = start(path);168 let mut job = peer.open(open(credit), &[]).expect("open");169 let (chunks, done) = drain(&mut job);170 drop(job);171 (chunks, done, peer, child, dir)172 }173 /// Closes the session and proves that the plugin exits on its own.174 fn finish(peer: Peer, mut child: Child) {175 peer.close().expect("close");176 assert!(child.wait().expect("wait").success());177 }178 #[test]179 fn a_job_replies_the_deterministic_token_sequence() {180 let path = weights(&["x", "a"], "zzz");181 let len = fs::metadata(&path).expect("the file exists").len();182 let (chunks, done, peer, child, _dir) = run(&path, CREDIT);183 assert_eq!(chunks, vec!["a".to_string(); TOKENS]);184 assert_eq!(done.outcome, body::Outcome::Completed);185 assert_eq!(done.usage.get("tokens_out"), Some(&(TOKENS as u64)));186 assert_eq!(done.usage.get("weights_bytes"), Some(&len));187 finish(peer, child);188 }189 #[test]190 fn a_stop_across_two_tokens_is_held_back() {191 let path = weights(&["x", "a"], "aa");192 let (chunks, done, peer, child, _dir) = run(&path, CREDIT);193 // The first `a` is a prefix of the stop, so it never reaches a client. The194 // second `a` completes the stop, which is stripped too.195 assert!(chunks.is_empty());196 assert_eq!(done.outcome, body::Outcome::Completed);197 assert_eq!(done.usage.get("tokens_out"), Some(&2));198 finish(peer, child);199 }200 #[test]201 fn a_cancelled_job_ends_cancelled() {202 let path = weights(&["x", "a"], "zzz");203 let (peer, child, _dir) = start(&path);204 // One byte of credit lets the first token out and then blocks the second,205 // so the cancel arrives while the decoder is still running.206 let mut job = peer.open(open(1), &[]).expect("open");207 assert!(matches!(job.next().expect("read"), Some(Item::Accepted(_))));208 match job.next().expect("read") {209 Some(Item::Event { data, .. }) => assert_eq!(data, b"a"),210 other => panic!("expected the first token, got {other:?}"),211 }212 job.cancel().expect("cancel");213 let (chunks, done) = drain(&mut job);214 assert!(chunks.is_empty(), "a cancelled job emits no further token");215 assert_eq!(done.outcome, body::Outcome::Cancelled);216 drop(job);217 finish(peer, child);218 }219 #[test]220 fn the_weight_file_is_read_only_and_unchanged() {221 let path = weights(&["x", "a"], "zzz");222 let before = fs::read(&path).expect("read the file");223 let mut permissions = fs::metadata(&path).expect("the file exists").permissions();224 permissions.set_mode(0o444);225 fs::set_permissions(&path, permissions).expect("make the file read-only");226 let (chunks, done, peer, child, _dir) = run(&path, CREDIT);227 assert_eq!(chunks.len(), TOKENS);228 assert_eq!(done.outcome, body::Outcome::Completed);229 assert_eq!(fs::read(&path).expect("read the file"), before);230 assert!(231 fs::metadata(&path)232 .expect("the file exists")233 .permissions()234 .readonly()235 );236 finish(peer, child);237 }