crates/edge/sdk/tests/serve.rs 31.2 KiB 1066 lines Raw
1 //! `serve()` against the caller half, over a real socket pair.2 //!3 //! This is the first test in the tree that drives a whole job: a peer connects,4 //! greets, loads, opens, and reads its events and its terminal frame. The5 //! plugin is a stub, because a model is not what this test is about.6 7 use std::collections::BTreeMap;8 use std::fs::File;9 use std::io::{Read as _, Seek, SeekFrom};10 use std::os::fd::AsFd;11 use std::os::unix::net::UnixStream;12 use std::process::Command;13 use std::sync::Arc;14 use std::sync::atomic::{AtomicBool, Ordering};15 use std::sync::mpsc;16 use std::thread;17 use std::time::Duration;18 19 use inf3r_plugin_sdk::capability::{Artifact, Failure, Report, Request};20 use inf3r_plugin_sdk::emitter::{EmitError, Emitter};21 use inf3r_plugin_sdk::serve::{Plugin, serve};22 use inf3r_proto::Value;23 use inf3r_proto::body::{24     self, Body, Capability, Catalogue, ErrorCode, Grant, Model, Open, PartKind, Ready, Target,25     VersionRange,26 };27 use inf3r_proto::client::{Item, Peer};28 use inf3r_proto::frame::{Header, Kind};29 use inf3r_proto::{recv_frame, send_frame};30 31 const WAIT: Duration = Duration::from_secs(5);32 const TEXT: &str = "text/plain; charset=utf-8";33 34 /// A plugin that echoes every text part and then says which parts it saw.35 struct Echo {36     /// When set, the job fails after the first chunk.37     fail: bool,38     /// When set, the job writes an artifact instead of a second chunk.39     artifact: bool,40 }41 42 impl Plugin for Echo {43     fn max_inflight(&self) -> u16 {44         245     }46 47     fn catalogue(&self) -> Catalogue {48         Catalogue {49             target: Target {50                 id: "cpu".into(),51                 backend: "mock".into(),52                 arch: vec!["x86_64".into()],53                 devices: 0,54                 vram_mb: Vec::new(),55             },56             models: vec![Model {57                 serve: "echo".into(),58                 alias_of: None,59                 weights_bytes: 0,60                 load_ms: 0,61                 capabilities: BTreeMap::from([(62                     "chat".to_string(),63                     Capability {64                         vocab: "chat.v1".into(),65                         parts: vec![PartKind::Text],66                         channels: vec!["text".into()],67                         limits: BTreeMap::new(),68                         cancel: Default::default(),69                         stops: Default::default(),70                         queue: Default::default(),71                     },72                 )]),73             }],74             runtime: None,75             cache: None,76         }77     }78 79     fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {80         Ok(Ready {81             load_ms: 7,82             cache_fingerprint: None,83         })84     }85 86     fn run(87         &self,88         capability: &str,89         req: Request<'_>,90         out: &mut dyn Emitter,91     ) -> Result<Report, Failure> {92         if capability != "chat" {93             return Err(Failure::capability(capability));94         }95         for part in req.parts {96             let Some(text) = part.text() else {97                 return Err(Failure::part("a part that is not text"));98             };99             out.emit("text", TEXT, text.as_bytes())100                 .map_err(|why| Failure::new(ErrorCode::Internal, why.to_string()))?;101         }102         if self.fail {103             return Err(Failure::new(ErrorCode::Internal, "the model stopped"));104         }105         if self.artifact {106             out.artifact("text", TEXT, Artifact::Bytes(b"artifact".to_vec()))107                 .map_err(|why| Failure::new(ErrorCode::Internal, why.to_string()))?;108         }109         let mut usage = BTreeMap::new();110         usage.insert("tokens_in".to_string(), 3);111         usage.insert("tokens_out".to_string(), 4);112         let mut meta = BTreeMap::new();113         meta.insert("finish_reason".to_string(), Value::Text("stop".into()));114         Ok(Report { usage, meta })115     }116 }117 118 fn open(credit: u64, text: &str) -> Open {119     open_for(credit, text, 5_000)120 }121 122 fn open_for(credit: u64, text: &str, budget_ms: u32) -> Open {123     Open {124         request_id: "r-1".into(),125         model: "echo".into(),126         capability: "chat".into(),127         credit,128         budget_ms,129         parts: vec![body::Part {130             kind: PartKind::Text,131             mime: TEXT.into(),132             role: None,133             len: text.len() as u64,134             hold: body::Hold::Inline(text.as_bytes().to_vec()),135         }],136         params: Value::Map(Vec::new()),137     }138 }139 140 /// Reads items until the terminal one.141 fn until_terminal(job: &mut inf3r_proto::client::Job) -> Item {142     loop {143         match job.next().unwrap() {144             Some(Item::Accepted(_)) | Some(Item::Event { .. }) => {}145             Some(item @ (Item::Done(..) | Item::Reject(_))) => return item,146             None => panic!("the stream ended without a terminal frame"),147         }148     }149 }150 151 /// Starts the plugin and returns the caller's peer, already loaded.152 fn peer<P: Plugin>(plugin: P) -> (Peer, thread::JoinHandle<std::io::Result<()>>) {153     let (caller, serving) = UnixStream::pair().unwrap();154     let served = thread::spawn(move || serve(serving, Arc::new(plugin)));155 156     let peer = Peer::connect(caller, "sdk-test", WAIT).unwrap();157     let grant = Grant { deps: Vec::new() };158     peer.load(&grant, WAIT).unwrap();159     (peer, served)160 }161 162 /// A raw caller, for frames that `Peer` will not send.163 struct Wire {164     socket: UnixStream,165 }166 167 impl Wire {168     fn send(&self, stream: u16, body: &Body) {169         let payload = body.encode();170         let length = match u32::try_from(payload.len()) {171             Ok(length) => length,172             Err(_) => panic!("the test body fits one frame"),173         };174         let header = Header::new(body.kind(), stream, length);175         send_frame(&self.socket, header, &payload, &[]).expect("the frame is written");176     }177 178     fn send_extension(&self, kind: u8, payload: &[u8]) {179         let header = Header::new(Kind::Extension(kind), 0, payload.len() as u32);180         send_frame(&self.socket, header, payload, &[]).expect("the frame is written");181     }182 183     fn recv(&self) -> (u16, Body) {184         let (frame, _) = recv_frame(&self.socket)185             .expect("the socket reads")186             .expect("a frame arrives");187         let body = Body::decode(frame.header.kind, &frame.payload).expect("the body decodes");188         (frame.header.stream, body)189     }190 191     fn handshake(&self) {192         self.send(193             0,194             &Body::Hello(body::Hello {195                 v: VersionRange { min: 1, max: 1 },196                 role: body::Role::Call,197                 id: "raw".into(),198             }),199         );200         assert!(matches!(self.recv().1, Body::Welcome(_)));201         assert!(matches!(self.recv().1, Body::Catalogue(_)));202         self.send(0, &Body::Grant(Grant { deps: Vec::new() }));203         assert!(matches!(self.recv().1, Body::Ready(_)));204     }205 }206 207 fn raw<P: Plugin>(plugin: Arc<P>) -> (Wire, thread::JoinHandle<std::io::Result<()>>) {208     let (caller, serving) = UnixStream::pair().unwrap();209     let served = thread::spawn(move || serve(serving, plugin));210     let wire = Wire { socket: caller };211     wire.handshake();212     (wire, served)213 }214 215 fn until_done(wire: &Wire, stream: u16) -> (Vec<String>, body::Done) {216     let mut events = Vec::new();217     loop {218         let (on, body) = wire.recv();219         if on != stream {220             continue;221         }222         match body {223             Body::Accept(_) => {}224             Body::Event(event) => {225                 events.push(String::from_utf8(event.data).expect("text is UTF-8"));226             }227             Body::Done(done) => return (events, done),228             other => panic!("expected a terminal frame, got {other:?}"),229         }230     }231 }232 233 fn expect_fatal(wire: &Wire, code: ErrorCode) {234     let (stream, body) = wire.recv();235     assert_eq!(stream, 0);236     match body {237         Body::Fatal(refusal) => assert_eq!(refusal.code, code),238         other => panic!("expected fatal{{{code}}}, got {other:?}"),239     }240 }241 242 /// True when `serve` returns before the limit.243 fn joined_within(served: thread::JoinHandle<std::io::Result<()>>, limit: Duration) -> bool {244     let (done, wait) = mpsc::channel();245     thread::spawn(move || {246         let _ = served.join();247         let _ = done.send(());248     });249     wait.recv_timeout(limit).is_ok()250 }251 252 /// A plugin whose one job blocks on credit until the socket wakes it.253 struct Blocked {254     finished: Arc<AtomicBool>,255 }256 257 impl Plugin for Blocked {258     fn max_inflight(&self) -> u16 {259         1260     }261 262     fn catalogue(&self) -> Catalogue {263         Catalogue {264             target: Target {265                 id: "cpu".into(),266                 backend: "mock".into(),267                 arch: vec!["x86_64".into()],268                 devices: 0,269                 vram_mb: Vec::new(),270             },271             models: vec![Model {272                 serve: "echo".into(),273                 alias_of: None,274                 weights_bytes: 0,275                 load_ms: 0,276                 capabilities: BTreeMap::from([(277                     "chat".to_string(),278                     Capability {279                         vocab: "chat.v1".into(),280                         parts: vec![PartKind::Text],281                         channels: vec!["text".into()],282                         limits: BTreeMap::new(),283                         cancel: Default::default(),284                         stops: Default::default(),285                         queue: Default::default(),286                     },287                 )]),288             }],289             runtime: None,290             cache: None,291         }292     }293 294     fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {295         Ok(Ready {296             load_ms: 0,297             cache_fingerprint: None,298         })299     }300 301     fn run(302         &self,303         _capability: &str,304         _req: Request<'_>,305         out: &mut dyn Emitter,306     ) -> Result<Report, Failure> {307         struct Finish(Arc<AtomicBool>);308         impl Drop for Finish {309             fn drop(&mut self) {310                 self.0.store(true, Ordering::SeqCst);311             }312         }313         let _finish = Finish(Arc::clone(&self.finished));314         match out.emit("text", TEXT, b"x") {315             Ok(_) => Ok(Report {316                 usage: BTreeMap::new(),317                 meta: BTreeMap::new(),318             }),319             Err(EmitError::Blocked) => {320                 Err(Failure::new(ErrorCode::Timeout, "the window never opened"))321             }322             Err(why) => Err(Failure::new(ErrorCode::Internal, why.to_string())),323         }324     }325 }326 327 #[test]328 fn a_job_streams_its_channels_and_ends_with_done() {329     let (peer, served) = peer(Echo {330         fail: false,331         artifact: false,332     });333     assert_eq!(peer.catalogue().unwrap().models[0].serve, "echo");334     assert_eq!(peer.welcome().unwrap().max_inflight, 2);335 336     let mut job = peer.open(open(64, "hello"), &[]).unwrap();337     assert!(matches!(job.next().unwrap(), Some(Item::Accepted(_))));338 339     let mut text = String::new();340     match job.next().unwrap() {341         Some(Item::Event { ch, data, .. }) => {342             assert_eq!(ch, "text");343             text.push_str(std::str::from_utf8(&data).unwrap());344         }345         other => panic!("expected an event, got {other:?}"),346     }347     assert_eq!(text, "hello");348 349     match job.next().unwrap() {350         Some(Item::Done(done, fds)) => {351             assert_eq!(done.outcome, body::Outcome::Completed);352             assert!(fds.is_empty());353             assert_eq!(done.usage.get("tokens_in"), Some(&3));354             assert_eq!(355                 done.meta356                     .as_ref()357                     .and_then(|meta| meta.get("finish_reason")),358                 Some(&Value::Text("stop".into()))359             );360         }361         other => panic!("expected done, got {other:?}"),362     }363     assert!(job.next().unwrap().is_none());364 365     peer.close().unwrap();366     served.join().unwrap().unwrap();367 }368 369 #[test]370 fn an_artifact_rides_with_the_terminal_frame() {371     let (peer, served) = peer(Echo {372         fail: false,373         artifact: true,374     });375     let mut job = peer.open(open(64, "x"), &[]).unwrap();376 377     match until_terminal(&mut job) {378         Item::Done(done, fds) => {379             assert_eq!(done.artifacts.len(), 1);380             assert_eq!(done.artifacts[0].ch, "text");381             assert_eq!(done.artifacts[0].len, 8);382             assert!(matches!(done.artifacts[0].hold, body::Hold::Inline(_)));383             assert!(fds.is_empty());384         }385         other => panic!("expected done, got {other:?}"),386     }387     peer.close().unwrap();388     served.join().unwrap().unwrap();389 }390 391 #[test]392 fn a_plugin_failure_after_accept_is_a_done_with_failed() {393     let (peer, served) = peer(Echo {394         fail: true,395         artifact: false,396     });397     let mut job = peer.open(open(64, "x"), &[]).unwrap();398 399     match until_terminal(&mut job) {400         Item::Done(done, _) => {401             assert_eq!(done.outcome, body::Outcome::Failed);402             assert_eq!(403                 done.meta.as_ref().and_then(|meta| meta.get("error")),404                 Some(&Value::Text("internal".into()))405             );406             assert_eq!(407                 done.meta.as_ref().and_then(|meta| meta.get("detail")),408                 Some(&Value::Text("the model stopped".into()))409             );410         }411         other => panic!("expected done{{failed}}, got {other:?}"),412     }413     peer.close().unwrap();414     served.join().unwrap().unwrap();415 }416 417 #[test]418 fn a_capability_that_the_plugin_does_not_serve_is_refused() {419     let (peer, served) = peer(Echo {420         fail: false,421         artifact: false,422     });423     let mut request = open(64, "x");424     request.capability = "music".into();425     let mut job = peer.open(request, &[]).unwrap();426 427     match until_terminal(&mut job) {428         Item::Reject(refusal) => assert_eq!(refusal.code, ErrorCode::Capability),429         other => panic!("expected reject{{capability}}, got {other:?}"),430     }431     peer.close().unwrap();432     served.join().unwrap().unwrap();433 }434 435 #[test]436 fn the_catalogue_of_describe_is_the_json_of_the_spec() {437     let plugin = Echo {438         fail: false,439         artifact: false,440     };441     let text = inf3r_plugin_sdk::catalogue_json(&plugin.catalogue());442     let value = inf3r_json::parse(&text).expect("describe prints JSON");443 444     assert_eq!(445         value446             .get("models")447             .and_then(|m| m.as_array())448             .map(|m| m.len()),449         Some(1)450     );451     assert_eq!(452         value453             .get("models")454             .and_then(|m| m.as_array())455             .and_then(|m| m[0].get("serve"))456             .and_then(|s| s.as_str()),457         Some("echo")458     );459     // The version and the limit that `welcome` carries are the same numbers.460     assert_eq!(461         value462             .get("target")463             .and_then(|t| t.get("id"))464             .and_then(|s| s.as_str()),465         Some("cpu")466     );467 }468 469 #[test]470 fn a_hello_without_our_version_ends_the_session() {471     let (caller, serving) = UnixStream::pair().unwrap();472     let served = thread::spawn(move || {473         serve(474             serving,475             Arc::new(Echo {476                 fail: false,477                 artifact: false,478             }),479         )480     });481 482     // Handshake by hand, so that the version range is the one under test.483     let hello = Body::Hello(body::Hello {484         v: VersionRange { min: 3, max: 4 },485         role: body::Role::Call,486         id: "old".into(),487     });488     let payload = hello.encode();489     let header = Header::new(Kind::Hello, 0, payload.len() as u32);490     inf3r_proto::send_frame(&caller, header, &payload, &[]).unwrap();491 492     let (frame, _) = inf3r_proto::recv_frame(&caller).unwrap().expect("a frame");493     let body = Body::decode(frame.header.kind, &frame.payload).unwrap();494     match body {495         Body::Fatal(refusal) => assert_eq!(refusal.code, ErrorCode::Version),496         other => panic!("expected fatal{{version}}, got {other:?}"),497     }498     drop(caller);499     served.join().unwrap().unwrap();500 }501 502 #[test]503 fn a_mismatched_runtime_version_fails_launch_before_serving() {504     let output = Command::new(env!("CARGO_BIN_EXE_runtime_probe"))505         .arg("--describe")506         .env("INF3R_RUNTIME_VERSION", "9.9")507         .output()508         .expect("the probe runs");509     assert!(!output.status.success());510     let stderr = String::from_utf8(output.stderr).expect("the error is UTF-8");511     assert!(stderr.contains("built for probe 1.0"), "{stderr}");512     assert!(stderr.contains("the runtime reports 9.9"), "{stderr}");513 }514 515 #[test]516 fn a_matching_runtime_version_starts() {517     let output = Command::new(env!("CARGO_BIN_EXE_runtime_probe"))518         .arg("--describe")519         .env("INF3R_RUNTIME_VERSION", "1.0")520         .output()521         .expect("the probe runs");522     assert!(output.status.success());523     let stdout = String::from_utf8(output.stdout).expect("the catalogue is UTF-8");524     assert!(stdout.contains("\"target\""), "{stdout}");525 }526 527 #[test]528 fn an_extension_frame_is_read_and_dropped() {529     let (caller, serving) = UnixStream::pair().unwrap();530     let served = thread::spawn(move || {531         serve(532             serving,533             Arc::new(Echo {534                 fail: false,535                 artifact: false,536             }),537         )538     });539     let wire = Wire { socket: caller };540     wire.send_extension(0x40, b"a future this build does not know");541 542     wire.handshake();543     wire.send(1, &Body::Open(open(64, "hello")));544     let (events, done) = until_done(&wire, 1);545     assert_eq!(events, ["hello"]);546     assert_eq!(done.outcome, body::Outcome::Completed);547 548     drop(wire);549     served.join().unwrap().unwrap();550 }551 552 #[test]553 fn a_bye_still_reads_a_window_until_the_jobs_end() {554     let (wire, served) = raw(Arc::new(Echo {555         fail: false,556         artifact: false,557     }));558     wire.send(1, &Body::Open(open_for(1, "hello", 5_000)));559     let (on, body) = wire.recv();560     assert_eq!(on, 1);561     assert!(matches!(body, Body::Accept(_)));562 563     wire.send(564         0,565         &Body::Bye(body::Bye {566             reason: String::new(),567         }),568     );569     wire.send(1, &Body::Window(body::Window { credit: 64 }));570 571     let (events, done) = until_done(&wire, 1);572     assert_eq!(events, ["hello"]);573     assert_eq!(done.outcome, body::Outcome::Completed);574 575     drop(wire);576     assert!(joined_within(served, WAIT), "the drain must end");577 }578 579 #[test]580 fn a_fatal_frame_wakes_a_worker_blocked_on_credit() {581     let finished = Arc::new(AtomicBool::new(false));582     let (wire, served) = raw(Arc::new(Blocked {583         finished: Arc::clone(&finished),584     }));585     wire.send(1, &Body::Open(open_for(0, "x", 5_000)));586     let (on, body) = wire.recv();587     assert_eq!(on, 1);588     assert!(matches!(body, Body::Accept(_)));589 590     wire.send(591         0,592         &Body::Fatal(body::Refusal {593             code: ErrorCode::Frame,594             detail: None,595         }),596     );597     assert!(joined_within(served, WAIT));598     assert!(599         finished.load(Ordering::SeqCst),600         "the worker must be awake before serve returns"601     );602 }603 604 #[test]605 fn an_abandoned_socket_wakes_a_worker_blocked_on_credit() {606     let finished = Arc::new(AtomicBool::new(false));607     let (wire, served) = raw(Arc::new(Blocked {608         finished: Arc::clone(&finished),609     }));610     wire.send(1, &Body::Open(open_for(0, "x", 30_000)));611     let (on, body) = wire.recv();612     assert_eq!(on, 1);613     assert!(matches!(body, Body::Accept(_)));614 615     drop(wire);616     assert!(617         joined_within(served, Duration::from_secs(2)),618         "a dead caller must not wait for the budget"619     );620     assert!(finished.load(Ordering::SeqCst));621 }622 623 #[test]624 fn a_window_below_the_granted_limit_is_a_fatal_credit() {625     let (wire, served) = raw(Arc::new(Echo {626         fail: false,627         artifact: false,628     }));629     wire.send(1, &Body::Open(open(64, &"x".repeat(100))));630     let (on, body) = wire.recv();631     assert_eq!(on, 1);632     assert!(matches!(body, Body::Accept(_)));633 634     wire.send(1, &Body::Window(body::Window { credit: 1 }));635     expect_fatal(&wire, ErrorCode::Credit);636 637     drop(wire);638     assert!(joined_within(served, WAIT));639 }640 641 #[test]642 fn an_unknown_window_is_a_fatal_stream() {643     let (wire, served) = raw(Arc::new(Echo {644         fail: false,645         artifact: false,646     }));647     wire.send(7, &Body::Window(body::Window { credit: 8 }));648     expect_fatal(&wire, ErrorCode::Stream);649 650     drop(wire);651     assert!(joined_within(served, WAIT));652 }653 654 #[test]655 fn a_cancel_ends_an_active_stream_at_once() {656     let finished = Arc::new(AtomicBool::new(false));657     let (wire, served) = raw(Arc::new(Blocked {658         finished: Arc::clone(&finished),659     }));660     wire.send(1, &Body::Open(open_for(0, "x", 5_000)));661     let (stream, body) = wire.recv();662     assert_eq!(stream, 1);663     assert!(matches!(body, Body::Accept(_)));664 665     wire.send(666         1,667         &Body::Cancel(body::CancelJob {668             reason: String::new(),669         }),670     );671     let (stream, body) = wire.recv();672     assert_eq!(stream, 1);673     match body {674         Body::Done(done) => assert_eq!(done.outcome, body::Outcome::Cancelled),675         other => panic!("expected done{{cancelled}}, got {other:?}"),676     }677 678     drop(wire);679     assert!(joined_within(served, WAIT));680     assert!(finished.load(Ordering::SeqCst));681 }682 683 #[test]684 fn an_unknown_cancel_is_a_fatal_stream() {685     let (wire, served) = raw(Arc::new(Echo {686         fail: false,687         artifact: false,688     }));689     wire.send(690         7,691         &Body::Cancel(body::CancelJob {692             reason: String::new(),693         }),694     );695     expect_fatal(&wire, ErrorCode::Stream);696 697     drop(wire);698     assert!(joined_within(served, WAIT));699 }700 701 #[test]702 fn an_open_on_stream_zero_is_a_fatal_stream() {703     let (wire, served) = raw(Arc::new(Echo {704         fail: false,705         artifact: false,706     }));707     wire.send(0, &Body::Open(open(64, "x")));708     expect_fatal(&wire, ErrorCode::Stream);709 710     drop(wire);711     assert!(joined_within(served, WAIT));712 }713 714 #[test]715 fn a_duplicate_stream_id_is_a_fatal_stream() {716     let (wire, served) = raw(Arc::new(Echo {717         fail: false,718         artifact: false,719     }));720     wire.send(1, &Body::Open(open_for(0, "x", 5_000)));721     let (on, body) = wire.recv();722     assert_eq!(on, 1);723     assert!(matches!(body, Body::Accept(_)));724 725     wire.send(1, &Body::Open(open(64, "x")));726     expect_fatal(&wire, ErrorCode::Stream);727 728     drop(wire);729     assert!(joined_within(served, WAIT));730 }731 732 #[test]733 fn an_open_above_max_inflight_is_rejected_busy() {734     let (wire, served) = raw(Arc::new(Echo {735         fail: false,736         artifact: false,737     }));738     for id in [1, 2] {739         wire.send(id, &Body::Open(open_for(0, "x", 5_000)));740         let (on, body) = wire.recv();741         assert_eq!(on, id);742         assert!(matches!(body, Body::Accept(_)));743     }744 745     wire.send(3, &Body::Open(open(64, "x")));746     let (on, body) = wire.recv();747     assert_eq!(on, 3);748     match body {749         Body::Reject(refusal) => assert_eq!(refusal.code, ErrorCode::Busy),750         other => panic!("expected reject{{busy}}, got {other:?}"),751     }752 753     drop(wire);754     assert!(joined_within(served, WAIT));755 }756 757 #[test]758 fn a_window_releases_a_worker_blocked_on_credit() {759     let (wire, served) = raw(Arc::new(Echo {760         fail: false,761         artifact: false,762     }));763     wire.send(1, &Body::Open(open_for(0, "ok", 5_000)));764     let (on, body) = wire.recv();765     assert_eq!(on, 1);766     assert!(matches!(body, Body::Accept(_)));767 768     wire.send(1, &Body::Window(body::Window { credit: 2 }));769     let (events, done) = until_done(&wire, 1);770     assert_eq!(events, ["ok"]);771     assert_eq!(done.outcome, body::Outcome::Completed);772 773     drop(wire);774     assert!(joined_within(served, WAIT));775 }776 777 #[test]778 fn a_window_for_a_skipped_stream_is_a_fatal_stream() {779     let (wire, served) = raw(Arc::new(Echo {780         fail: false,781         artifact: false,782     }));783     wire.send(5, &Body::Open(open_for(0, "x", 5_000)));784     let (on, body) = wire.recv();785     assert_eq!(on, 5);786     assert!(matches!(body, Body::Accept(_)));787 788     // Stream 3 was never opened. It is unknown even though 5 came after it.789     wire.send(3, &Body::Window(body::Window { credit: 8 }));790     expect_fatal(&wire, ErrorCode::Stream);791 792     drop(wire);793     assert!(joined_within(served, WAIT));794 }795 796 /// A plugin that reads every part through the bounded reader.797 struct FileEcho(Echo);798 799 impl Plugin for FileEcho {800     fn max_inflight(&self) -> u16 {801         self.0.max_inflight()802     }803 804     fn catalogue(&self) -> Catalogue {805         self.0.catalogue()806     }807 808     fn load(&self, grant: &Grant) -> Result<Ready, Failure> {809         self.0.load(grant)810     }811 812     fn run(813         &self,814         _capability: &str,815         req: Request<'_>,816         out: &mut dyn Emitter,817     ) -> Result<Report, Failure> {818         for part in req.parts {819             if part.bytes().is_some() || part.file().is_none() {820                 return Err(Failure::part("the part did not arrive as a descriptor"));821             }822             let mut bytes = Vec::new();823             part.reader()824                 .read_to_end(&mut bytes)825                 .map_err(|why| Failure::part(why.to_string()))?;826             out.emit("text", TEXT, &bytes)827                 .map_err(|why| Failure::new(ErrorCode::Internal, why.to_string()))?;828         }829         Ok(Report::default())830     }831 }832 833 /// A plugin that refuses every job in `admit`, before `accept`.834 struct Refuser(Echo);835 836 impl Plugin for Refuser {837     fn max_inflight(&self) -> u16 {838         self.0.max_inflight()839     }840 841     fn catalogue(&self) -> Catalogue {842         self.0.catalogue()843     }844 845     fn load(&self, grant: &Grant) -> Result<Ready, Failure> {846         self.0.load(grant)847     }848 849     fn admit(&self, req: &Request<'_>) -> Result<(), Failure> {850         Err(Failure::new(851             ErrorCode::Part,852             format!("{} is not admissible", req.model),853         ))854     }855 856     fn run(857         &self,858         capability: &str,859         req: Request<'_>,860         out: &mut dyn Emitter,861     ) -> Result<Report, Failure> {862         self.0.run(capability, req, out)863     }864 }865 866 /// A plugin that serves one alias and says which name the request carried.867 struct ModelEcho(Echo);868 869 impl Plugin for ModelEcho {870     fn max_inflight(&self) -> u16 {871         self.0.max_inflight()872     }873 874     fn catalogue(&self) -> Catalogue {875         let mut catalogue = self.0.catalogue();876         let mut alias = catalogue.models[0].clone();877         alias.serve = "alias".to_string();878         alias.alias_of = Some("echo".to_string());879         catalogue.models.push(alias);880         catalogue881     }882 883     fn load(&self, grant: &Grant) -> Result<Ready, Failure> {884         self.0.load(grant)885     }886 887     fn run(888         &self,889         _capability: &str,890         req: Request<'_>,891         out: &mut dyn Emitter,892     ) -> Result<Report, Failure> {893         out.emit("text", TEXT, req.model.as_bytes())894             .map_err(|why| Failure::new(ErrorCode::Internal, why.to_string()))?;895         Ok(Report::default())896     }897 }898 899 fn file_with(name: &str, bytes: &[u8]) -> std::path::PathBuf {900     let path = std::env::temp_dir().join(format!("inf3r-sdk-{name}-{}", std::process::id()));901     std::fs::write(&path, bytes).expect("the test file is written");902     path903 }904 905 #[test]906 fn an_admission_failure_is_a_reject_without_an_accept() {907     let (peer, served) = peer(Refuser(Echo {908         fail: false,909         artifact: false,910     }));911     let mut job = peer.open(open(64, "x"), &[]).unwrap();912 913     match job.next().unwrap() {914         Some(Item::Reject(refusal)) => {915             assert_eq!(refusal.code, ErrorCode::Part);916             assert_eq!(refusal.detail.as_deref(), Some("echo is not admissible"));917         }918         other => panic!("expected reject before accept, got {other:?}"),919     }920     assert!(job.next().unwrap().is_none());921 922     peer.close().unwrap();923     served.join().unwrap().unwrap();924 }925 926 #[test]927 fn the_request_carries_the_served_name() {928     let (peer, served) = peer(ModelEcho(Echo {929         fail: false,930         artifact: false,931     }));932     let mut request = open(64, "x");933     request.model = "alias".to_string();934     let mut job = peer.open(request, &[]).unwrap();935 936     assert!(matches!(job.next().unwrap(), Some(Item::Accepted(_))));937     match job.next().unwrap() {938         Some(Item::Event { ch, data, .. }) => {939             assert_eq!(ch, "text");940             assert_eq!(data, b"alias");941         }942         other => panic!("expected an event, got {other:?}"),943     }944     assert!(matches!(945         job.next().unwrap(),946         Some(Item::Done(done, _)) if done.outcome == body::Outcome::Completed947     ));948 949     peer.close().unwrap();950     served.join().unwrap().unwrap();951 }952 953 #[test]954 fn a_file_part_starts_at_zero_and_stops_at_its_declared_length() {955     let path = file_with("file-part", b"hello world");956     let (peer, served) = peer(FileEcho(Echo {957         fail: false,958         artifact: false,959     }));960 961     let mut request = open(64, "");962     request.parts = vec![body::Part {963         kind: PartKind::Text,964         mime: TEXT.into(),965         role: None,966         len: 5,967         hold: body::Hold::Fd(0),968     }];969     let mut file = File::open(&path).expect("the test file opens");970     file.seek(SeekFrom::Start(3)).expect("the offset moves");971 972     let mut job = peer.open(request, &[file.as_fd()]).unwrap();973     assert!(matches!(job.next().unwrap(), Some(Item::Accepted(_))));974     match job.next().unwrap() {975         Some(Item::Event { data, .. }) => assert_eq!(data, b"hello"),976         other => panic!("expected the bounded bytes, got {other:?}"),977     }978     assert!(matches!(979         job.next().unwrap(),980         Some(Item::Done(done, _)) if done.outcome == body::Outcome::Completed981     ));982 983     peer.close().unwrap();984     served.join().unwrap().unwrap();985     let _ = std::fs::remove_file(path);986 }987 988 #[test]989 fn a_short_file_part_is_rejected_before_accept() {990     let path = file_with("short-part", b"hi");991     let (peer, served) = peer(FileEcho(Echo {992         fail: false,993         artifact: false,994     }));995 996     let mut request = open(64, "");997     request.parts = vec![body::Part {998         kind: PartKind::Text,999         mime: TEXT.into(),1000         role: None,1001         len: 5,1002         hold: body::Hold::Fd(0),1003     }];1004     let file = File::open(&path).expect("the test file opens");1005     let mut job = peer.open(request, &[file.as_fd()]).unwrap();1006 1007     match job.next().unwrap() {1008         Some(Item::Reject(refusal)) => assert_eq!(refusal.code, ErrorCode::Part),1009         other => panic!("expected reject{{part}} before accept, got {other:?}"),1010     }1011 1012     peer.close().unwrap();1013     served.join().unwrap().unwrap();1014     let _ = std::fs::remove_file(path);1015 }1016 1017 #[test]1018 fn a_job_that_runs_out_of_budget_is_expired() {1019     let (wire, served) = raw(Arc::new(Blocked {1020         finished: Arc::new(AtomicBool::new(false)),1021     }));1022     wire.send(1, &Body::Open(open_for(0, "x", 30)));1023     let (on, body) = wire.recv();1024     assert_eq!(on, 1);1025     assert!(matches!(body, Body::Accept(_)));1026 1027     let (events, done) = until_done(&wire, 1);1028     assert!(events.is_empty());1029     assert_eq!(done.outcome, body::Outcome::Expired);1030 1031     drop(wire);1032     assert!(joined_within(served, WAIT));1033 }1034 1035 #[test]1036 fn a_missing_runtime_version_fails_launch_before_serving() {1037     let output = Command::new(env!("CARGO_BIN_EXE_runtime_probe"))1038         .arg("--describe")1039         .env_remove("INF3R_RUNTIME_VERSION")1040         .output()1041         .expect("the probe runs");1042     assert!(!output.status.success());1043     let stderr = String::from_utf8(output.stderr).expect("the error is UTF-8");1044     assert!(1045         stderr.contains("the runtime reports no version"),1046         "{stderr}"1047     );1048 }1049 1050 #[test]1051 fn a_wire_1_peer_never_receives_a_cache_frame() {1052     let (wire, served) = raw(Arc::new(Echo {1053         fail: false,1054         artifact: false,1055     }));1056     wire.send(1057         0,1058         &Body::CacheFlush(body::CacheFlush {1059             req_id: 1,1060             budget_ms: 10,1061         }),1062     );1063     expect_fatal(&wire, ErrorCode::Frame);1064     drop(wire);1065     served.join().unwrap().unwrap();1066 }