1 //! The core against a plugin that is already running.2 //!3 //! The plugin is the SDK's own test shape: it echoes text and answers the4 //! catalogue. What this test proves is the part between the two — the served5 //! name, the capability check, the parts check, and the slot.6 7 use std::collections::{BTreeMap, BTreeSet};8 use std::os::fd::OwnedFd;9 use std::os::unix::net::UnixStream;10 use std::sync::atomic::{AtomicBool, Ordering};11 use std::sync::{Arc, Mutex, mpsc};12 use std::thread;13 use std::time::{Duration, Instant};14 15 use inf3r_core::{16 Core, CoreError, JobState, Loader, Priority, RefusalCode, Served, Settle, Submit, Wait,17 };18 use inf3r_plugin_sdk::capability::{Failure, Report, Request};19 use inf3r_plugin_sdk::emitter::Emitter;20 use inf3r_plugin_sdk::serve::{Plugin, serve};21 use inf3r_proto::Value;22 use inf3r_proto::body::{23 self, Body, Capability, Catalogue, Grant, Model, PartKind, Ready, Target, Welcome,24 };25 use inf3r_proto::client::Item;26 use inf3r_proto::fd::{recv_frame, send_frame};27 use inf3r_proto::frame::{Header, Kind};28 use inf3r_supervisor::Failure as SuperFailure;29 30 const WAIT: Duration = Duration::from_secs(5);31 32 /// A plugin that echoes every text part. The cancel is the knob that the33 /// degraded test turns.34 struct Echo(body::Cancel);35 36 impl Plugin for Echo {37 fn max_inflight(&self) -> u16 {38 139 }40 41 fn catalogue(&self) -> Catalogue {42 Catalogue {43 runtime: None,44 target: Target {45 id: "cpu".into(),46 backend: "mock".into(),47 arch: vec![std::env::consts::ARCH.into()],48 devices: 0,49 vram_mb: Vec::new(),50 },51 models: vec![Model {52 serve: "echo".into(),53 alias_of: None,54 weights_bytes: 0,55 load_ms: 0,56 capabilities: BTreeMap::from([(57 "chat".to_string(),58 Capability {59 vocab: "chat.v1".into(),60 parts: vec![PartKind::Text],61 channels: vec!["text".into()],62 limits: BTreeMap::new(),63 cancel: self.0.clone(),64 stops: body::Stops::default(),65 queue: body::Queue::default(),66 },67 )]),68 }],69 cache: None,70 }71 }72 73 fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {74 Ok(Ready {75 load_ms: 3,76 cache_fingerprint: None,77 })78 }79 80 fn run(81 &self,82 _capability: &str,83 req: Request<'_>,84 out: &mut dyn Emitter,85 ) -> Result<Report, Failure> {86 for part in req.parts {87 out.emit(88 "text",89 "text/plain; charset=utf-8",90 part.bytes().unwrap_or_default(),91 )92 .map_err(|why| Failure::new(body::ErrorCode::Internal, why.to_string()))?;93 }94 Ok(Report::default())95 }96 }97 98 /// A plugin that records the length of the descriptor in its grant.99 struct Recorder {100 seen: Arc<Mutex<Option<u64>>>,101 }102 103 impl Plugin for Recorder {104 fn max_inflight(&self) -> u16 {105 1106 }107 108 fn catalogue(&self) -> Catalogue {109 Catalogue {110 runtime: None,111 target: Target {112 id: "cpu".into(),113 backend: "mock".into(),114 arch: vec![std::env::consts::ARCH.into()],115 devices: 0,116 vram_mb: Vec::new(),117 },118 models: Vec::new(),119 cache: None,120 }121 }122 123 fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {124 Ok(Ready {125 load_ms: 0,126 cache_fingerprint: None,127 })128 }129 130 fn load_fds(&self, _grant: &Grant, fds: &[OwnedFd]) -> Result<Ready, Failure> {131 let file = std::fs::File::from(fds[0].try_clone().unwrap());132 *self.seen.lock().unwrap() = Some(file.metadata().unwrap().len());133 Ok(Ready {134 load_ms: 0,135 cache_fingerprint: None,136 })137 }138 139 fn run(140 &self,141 capability: &str,142 _req: Request<'_>,143 _out: &mut dyn Emitter,144 ) -> Result<Report, Failure> {145 Err(Failure::capability(capability))146 }147 }148 149 #[test]150 fn a_connect_sends_the_weight_descriptor() {151 let path = std::env::temp_dir().join(format!("inf3r-core-weights-{}", std::process::id()));152 std::fs::write(&path, vec![1u8; 512]).unwrap();153 let seen = Arc::new(Mutex::new(None));154 let (caller, serving) = UnixStream::pair().unwrap();155 let plugin = Recorder { seen: seen.clone() };156 let served = thread::spawn(move || serve(serving, Arc::new(plugin)));157 158 let peer =159 Served::connect("rec", caller, "rec", std::slice::from_ref(&path), WAIT).expect("connect");160 assert_eq!(*seen.lock().unwrap(), Some(512));161 162 drop(peer);163 drop(served);164 let _ = std::fs::remove_file(&path);165 }166 167 #[test]168 fn a_missing_weight_path_is_load_failed_and_names_it() {169 let path = std::env::temp_dir().join(format!("inf3r-core-missing-{}", std::process::id()));170 let _ = std::fs::remove_file(&path);171 let (caller, _serving) = UnixStream::pair().unwrap();172 173 let Err(err) = Served::connect("rec", caller, "rec", std::slice::from_ref(&path), WAIT) else {174 panic!("a missing weight path must be refused")175 };176 assert_eq!(err.code(), RefusalCode::LoadFailed);177 assert_eq!(err.failure(), Some(SuperFailure::Dependency));178 assert!(179 err.to_string()180 .contains(&path.to_string_lossy().to_string()),181 "{err}"182 );183 }184 185 /// A plugin that accepts and then waits until the test lets it return.186 struct Hang {187 stop: Arc<AtomicBool>,188 }189 190 impl Plugin for Hang {191 fn max_inflight(&self) -> u16 {192 1193 }194 195 fn catalogue(&self) -> Catalogue {196 Catalogue {197 runtime: None,198 target: Target {199 id: "cpu".into(),200 backend: "mock".into(),201 arch: vec![std::env::consts::ARCH.into()],202 devices: 0,203 vram_mb: Vec::new(),204 },205 models: vec![Model {206 serve: "hang".into(),207 alias_of: None,208 weights_bytes: 0,209 load_ms: 0,210 capabilities: BTreeMap::from([(211 "chat".to_string(),212 Capability {213 vocab: "chat.v1".into(),214 parts: vec![PartKind::Text],215 channels: vec!["text".into()],216 limits: BTreeMap::new(),217 cancel: body::Cancel::default(),218 stops: body::Stops::default(),219 queue: body::Queue::default(),220 },221 )]),222 }],223 cache: None,224 }225 }226 227 fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {228 Ok(Ready {229 load_ms: 1,230 cache_fingerprint: None,231 })232 }233 234 fn run(235 &self,236 _capability: &str,237 _req: Request<'_>,238 _out: &mut dyn Emitter,239 ) -> Result<Report, Failure> {240 while !self.stop.load(Ordering::SeqCst) {241 thread::sleep(Duration::from_millis(10));242 }243 Ok(Report::default())244 }245 }246 247 /// A plugin that serves one model and one alias of it.248 struct Aliased;249 250 impl Plugin for Aliased {251 fn max_inflight(&self) -> u16 {252 1253 }254 255 fn catalogue(&self) -> Catalogue {256 let model = |serve: &str, alias_of: Option<&str>, capabilities| Model {257 serve: serve.to_string(),258 alias_of: alias_of.map(str::to_string),259 weights_bytes: 0,260 load_ms: 0,261 capabilities,262 };263 let chat = || {264 BTreeMap::from([(265 "chat".to_string(),266 Capability {267 vocab: "chat.v1".into(),268 parts: vec![PartKind::Text],269 channels: vec!["text".into()],270 limits: BTreeMap::new(),271 cancel: body::Cancel::default(),272 stops: body::Stops::default(),273 queue: body::Queue::default(),274 },275 )])276 };277 Catalogue {278 runtime: None,279 target: Target {280 id: "cpu".into(),281 backend: "mock".into(),282 arch: vec![std::env::consts::ARCH.into()],283 devices: 0,284 vram_mb: Vec::new(),285 },286 models: vec![287 model("base", None, chat()),288 model("alias", Some("base"), BTreeMap::new()),289 ],290 cache: None,291 }292 }293 294 fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {295 Ok(Ready {296 load_ms: 1,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 for part in req.parts {308 out.emit(309 "text",310 "text/plain; charset=utf-8",311 part.bytes().unwrap_or_default(),312 )313 .map_err(|why| Failure::new(body::ErrorCode::Internal, why.to_string()))?;314 }315 Ok(Report::default())316 }317 }318 319 /// A core with one served peer on a socket pair.320 fn core() -> (Core, thread::JoinHandle<std::io::Result<()>>) {321 let (caller, serving) = UnixStream::pair().unwrap();322 let served = thread::spawn(move || serve(serving, Arc::new(Echo(body::Cancel::default()))));323 324 let peer = Served::connect("echo", caller, "core-test", &[], WAIT).expect("connect");325 let core = Core::new();326 core.register(peer).expect("register");327 (core, served)328 }329 330 fn text_part(text: &str) -> body::Part {331 body::Part {332 kind: PartKind::Text,333 mime: "text/plain; charset=utf-8".into(),334 role: Some("user".into()),335 len: text.len() as u64,336 hold: body::Hold::Inline(text.as_bytes().to_vec()),337 }338 }339 340 fn submit(model: &str, capability: &str, parts: Vec<body::Part>) -> Submit {341 Submit {342 model: model.into(),343 capability: capability.into(),344 parts,345 files: Vec::new(),346 params: Value::Map(Vec::new()),347 request_id: "r-1".into(),348 credit: 1024,349 budget: WAIT,350 priority: Priority::Interactive,351 }352 }353 354 /// A core whose one capability stops only between requests, which is the355 /// declared degradation that a background job may not use.356 fn degraded_core() -> (Core, thread::JoinHandle<std::io::Result<()>>) {357 let (caller, serving) = UnixStream::pair().unwrap();358 let served = thread::spawn(move || serve(serving, Arc::new(Echo(body::Cancel::Request))));359 360 let peer = Served::connect("echo", caller, "core-test", &[], WAIT).expect("connect");361 let core = Core::new();362 core.register(peer).expect("register");363 (core, served)364 }365 366 /// Reads a job to its terminal frame and returns the text that it streamed.367 fn drain(mut job: inf3r_core::CoreJob) -> (String, body::Done) {368 let mut text = String::new();369 loop {370 match job.next().expect("read").expect("an item") {371 Item::Accepted(_) => {}372 Item::Event { data, .. } => text.push_str(std::str::from_utf8(&data).unwrap()),373 Item::Done(done, _) => return (text, done),374 Item::Reject(refusal) => panic!("refused: {refusal:?}"),375 }376 }377 }378 379 #[test]380 fn a_job_reaches_its_plugin_and_streams_back() {381 let (core, served) = core();382 let served_peer = core.served("echo").expect("the peer");383 assert_eq!(served_peer.load_ms(), Some(3));384 385 let job = core386 .submit(submit("echo", "chat", vec![text_part("hello")]))387 .expect("submit");388 let (text, done) = drain(job);389 assert_eq!(text, "hello");390 assert_eq!(done.outcome, body::Outcome::Completed);391 392 // The slot is given back when the job ends, and the schedule is the count.393 assert_eq!(core.sched().in_flight("echo"), 0);394 let _ = served_peer;395 396 drop(core);397 drop(served);398 }399 400 #[test]401 fn an_unknown_model_is_refused_before_a_slot() {402 let (core, _served) = core();403 let err = core404 .submit(submit("absent", "chat", vec![text_part("x")]))405 .unwrap_err();406 assert!(407 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::UnknownModel)408 );409 }410 411 #[test]412 fn a_capability_that_the_model_does_not_declare_is_refused() {413 let (core, _served) = core();414 let err = core415 .submit(submit("echo", "music", vec![text_part("x")]))416 .unwrap_err();417 assert!(418 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::UnknownCapability)419 );420 }421 422 #[test]423 fn a_part_that_the_capability_does_not_take_is_refused() {424 let (core, _served) = core();425 let mut image = text_part("x");426 image.kind = PartKind::Image;427 let err = core428 .submit(submit("echo", "chat", vec![image]))429 .unwrap_err();430 assert!(431 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::InvalidPart)432 );433 }434 435 #[test]436 fn a_declared_length_that_is_not_the_length_is_refused() {437 let (core, _served) = core();438 let mut part = text_part("hello");439 part.len = 4;440 let err = core.submit(submit("echo", "chat", vec![part])).unwrap_err();441 assert!(442 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::InvalidPart)443 );444 }445 446 #[test]447 fn a_job_whose_budget_is_spent_is_a_timeout() {448 let (core, _served) = core();449 450 // The first job holds the only slot of the plugin.451 let held = core452 .submit(submit("echo", "chat", vec![text_part("one")]))453 .expect("the first job");454 455 // A zero budget cannot wait for the slot, so the second is refused.456 let mut second = submit("echo", "chat", vec![text_part("two")]);457 second.budget = Duration::ZERO;458 let err = core.submit(second).unwrap_err();459 assert!(460 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::Timeout),461 "{err:?}"462 );463 464 drop(held);465 }466 467 #[test]468 fn two_peers_cannot_serve_one_name() {469 let (caller, serving) = UnixStream::pair().unwrap();470 let thread_a = thread::spawn(move || serve(serving, Arc::new(Echo(body::Cancel::default()))));471 let (caller_b, serving_b) = UnixStream::pair().unwrap();472 let thread_b = thread::spawn(move || serve(serving_b, Arc::new(Echo(body::Cancel::default()))));473 474 let core = Core::new();475 core.register(Served::connect("a", caller, "a", &[], WAIT).unwrap())476 .expect("the first peer");477 let err = core478 .register(Served::connect("b", caller_b, "b", &[], WAIT).unwrap())479 .unwrap_err();480 assert_eq!(err.code(), RefusalCode::AmbiguousModel);481 482 drop(core);483 drop(thread_a);484 drop(thread_b);485 }486 487 #[test]488 fn a_background_job_on_a_degraded_capability_is_refused_and_an_interactive_one_is_served() {489 let (core, served) = degraded_core();490 491 let mut background = submit("echo", "chat", vec![text_part("hidden")]);492 background.priority = Priority::Background;493 let err = core.submit(background).unwrap_err();494 assert!(495 matches!(496 &err,497 CoreError::Refused(refusal)498 if refusal.code == RefusalCode::CapabilityMissing499 && refusal.message == "echo cannot serve a background job: chat is degraded"500 ),501 "{err:?}"502 );503 504 let job = core505 .submit(submit("echo", "chat", vec![text_part("shown")]))506 .expect("an interactive job is served");507 let (text, done) = drain(job);508 assert_eq!(text, "shown");509 assert_eq!(done.outcome, body::Outcome::Completed);510 511 drop(core);512 drop(served);513 }514 515 /// A plugin whose served name and weights the test chooses.516 struct Named {517 name: String,518 weights: u64,519 context: u64,520 kv: u64,521 }522 523 impl Plugin for Named {524 fn max_inflight(&self) -> u16 {525 1526 }527 528 fn catalogue(&self) -> Catalogue {529 Catalogue {530 runtime: None,531 target: Target {532 id: "cpu".into(),533 backend: "mock".into(),534 arch: vec![std::env::consts::ARCH.into()],535 devices: 0,536 vram_mb: Vec::new(),537 },538 models: vec![Model {539 serve: self.name.clone(),540 alias_of: None,541 weights_bytes: self.weights,542 load_ms: 0,543 capabilities: BTreeMap::from([(544 "chat".to_string(),545 Capability {546 vocab: "chat.v1".into(),547 parts: vec![PartKind::Text],548 channels: vec!["text".into()],549 limits: [("context", self.context), ("kv_bytes_per_token", self.kv)]550 .into_iter()551 .filter(|(_, value)| *value != 0)552 .map(|(key, value)| (key.to_string(), value))553 .collect(),554 cancel: body::Cancel::default(),555 stops: body::Stops::default(),556 queue: body::Queue::default(),557 },558 )]),559 }],560 cache: None,561 }562 }563 564 fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {565 Ok(Ready {566 load_ms: 1,567 cache_fingerprint: None,568 })569 }570 571 fn run(572 &self,573 _capability: &str,574 req: Request<'_>,575 out: &mut dyn Emitter,576 ) -> Result<Report, Failure> {577 for part in req.parts {578 out.emit(579 "text",580 "text/plain; charset=utf-8",581 part.bytes().unwrap_or_default(),582 )583 .map_err(|why| Failure::new(body::ErrorCode::Internal, why.to_string()))?;584 }585 out.usage("tokens_out", 7);586 out.usage("first_token_ms", 12);587 out.usage("tokens_per_s", 345);588 Ok(Report::default())589 }590 }591 592 /// A core whose stop path does not wait for a real driver. The fixtures use593 /// device names that this machine may not have, and the ledger tests are not594 /// tests of the settle budget.595 fn core_with(loader: Arc<dyn Loader>) -> Core {596 let core = Core::with_loader(loader);597 core.residency().set_settle(Settle {598 budget: Duration::ZERO,599 step: Duration::from_millis(1),600 });601 core602 }603 604 fn fixture(name: &str, weights: u64) -> (Served, thread::JoinHandle<std::io::Result<()>>) {605 fixture_with(name, weights, 0, 0)606 }607 608 fn fixture_with(609 name: &str,610 weights: u64,611 context: u64,612 kv: u64,613 ) -> (Served, thread::JoinHandle<std::io::Result<()>>) {614 let (caller, serving) = UnixStream::pair().unwrap();615 let plugin = Named {616 name: name.to_string(),617 weights,618 context,619 kv,620 };621 let served = thread::spawn(move || serve(serving, Arc::new(plugin)));622 let peer = Served::connect(name, caller, name, &[], WAIT).expect("connect the fixture");623 (peer, served)624 }625 626 #[derive(Default)]627 struct FakeLoader {628 stops: Mutex<Vec<String>>,629 starts: Mutex<Vec<String>>,630 stop_fails: Mutex<BTreeSet<String>>,631 start_fails: Mutex<BTreeSet<String>>,632 exits: Mutex<BTreeMap<String, SuperFailure>>,633 start_failures: Mutex<BTreeMap<String, SuperFailure>>,634 }635 636 impl FakeLoader {637 fn fail_stop(&self, plugin: &str) {638 self.stop_fails.lock().unwrap().insert(plugin.to_string());639 }640 641 fn fail_start(&self, plugin: &str) {642 self.start_fails.lock().unwrap().insert(plugin.to_string());643 }644 645 fn exit_fails(&self, plugin: &str, failure: SuperFailure) {646 self.exits647 .lock()648 .unwrap()649 .insert(plugin.to_string(), failure);650 }651 652 fn fail_start_with(&self, plugin: &str, failure: SuperFailure) {653 self.fail_start(plugin);654 self.start_failures655 .lock()656 .unwrap()657 .insert(plugin.to_string(), failure);658 }659 660 fn stops(&self) -> Vec<String> {661 self.stops.lock().unwrap().clone()662 }663 }664 665 impl Loader for FakeLoader {666 fn start_failure(&self, plugin: &str) -> Option<SuperFailure> {667 self.start_failures.lock().unwrap().remove(plugin)668 }669 670 fn exit(&self, plugin: &str) -> Result<Option<SuperFailure>, String> {671 Ok(self.exits.lock().unwrap().remove(plugin))672 }673 674 fn stop(&self, plugin: &str) -> Result<(), String> {675 self.stops.lock().unwrap().push(plugin.to_string());676 if self.stop_fails.lock().unwrap().contains(plugin) {677 return Err("the fake stop".to_string());678 }679 Ok(())680 }681 682 fn start(&self, plugin: &str) -> Result<Served, String> {683 self.starts.lock().unwrap().push(plugin.to_string());684 if self.start_fails.lock().unwrap().contains(plugin) {685 return Err("the fake start".to_string());686 }687 let (served, _thread) = fixture(plugin, 0);688 Ok(served)689 }690 }691 692 fn reserve_for(core: &Core, plugin: &str, device: &str, bytes: u64) {693 let wants = BTreeMap::from([(device.to_string(), bytes)]);694 let reservation = core.residency().reserve(&wants).expect("the fixture fits");695 core.residency().hold(plugin, reservation);696 }697 698 fn release_all(core: &Core, plugins: &[&str], device: &str) {699 for plugin in plugins {700 if let Some(reservation) = core.residency().release_plugin(plugin) {701 core.residency().release(reservation);702 }703 }704 assert_eq!(core.residency().held(device), 0);705 }706 707 #[test]708 fn an_idle_plugin_is_stopped_and_released_but_a_pin_or_a_job_is_not() {709 let loader = Arc::new(FakeLoader::default());710 let core = core_with(loader.clone());711 for name in ["a", "b", "c"] {712 let (served, _thread) = fixture(name, 0);713 core.register(served).expect("register");714 }715 core.residency().declare("cuda:0", 100);716 for name in ["a", "b", "c"] {717 reserve_for(&core, name, "cuda:0", 1);718 core.residency()719 .declare_intent(name, name == "c", Some(Duration::from_millis(1)));720 }721 722 let busy = BTreeSet::from(["b".to_string()]);723 let now = Instant::now() + Duration::from_secs(1);724 assert_eq!(core.sweep_idle(now, &busy), vec!["a".to_string()]);725 726 assert!(core.served("a").is_none());727 assert!(core.served("b").is_some());728 assert!(core.served("c").is_some());729 assert_eq!(loader.stops(), vec!["a".to_string()]);730 assert_eq!(core.residency().held("cuda:0"), 2);731 732 release_all(&core, &["b", "c"], "cuda:0");733 }734 735 #[test]736 fn the_bind_priority_is_the_default_for_a_request_that_names_none() {737 let (core, served) = degraded_core();738 core.set_priority("echo", Priority::Background);739 740 let err = core741 .submit(submit("echo", "chat", vec![text_part("shown")]))742 .unwrap_err();743 assert!(744 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::CapabilityMissing),745 "{err:?}"746 );747 748 drop(core);749 drop(served);750 }751 752 #[test]753 fn a_bind_slot_count_cannot_raise_the_welcome() {754 let (caller, serving) = UnixStream::pair().unwrap();755 let served = thread::spawn(move || serve(serving, Arc::new(Echo(body::Cancel::default()))));756 let peer = Served::connect("echo", caller, "core-test", &[], WAIT).expect("connect");757 let core = Core::new();758 core.set_max_inflight("echo", 2);759 core.register(peer).expect("register");760 assert_eq!(core.engines()[0].slots, 1);761 762 drop(core);763 drop(served);764 }765 766 #[test]767 fn a_cold_load_keeps_the_idle_intent_and_can_be_swept() {768 let loader = Arc::new(FakeLoader::default());769 let core = core_with(loader.clone());770 let catalogue = Named {771 name: "a".into(),772 weights: 0,773 context: 0,774 kv: 0,775 }776 .catalogue();777 core.register_cold("a", &catalogue, 1)778 .expect("cold register");779 core.residency()780 .declare_intent("a", false, Some(Duration::from_millis(1)));781 782 let job = core783 .submit(submit("a", "chat", vec![text_part("cold")]))784 .expect("the cold load admits");785 let (text, _done) = drain(job);786 assert_eq!(text, "cold");787 thread::sleep(Duration::from_millis(5));788 789 assert_eq!(core.sweep_idle_now(), vec!["a".to_string()]);790 assert!(core.served("a").is_none());791 }792 793 #[test]794 fn sweep_idle_now_reads_the_core_clock_and_its_own_busy_set() {795 let loader = Arc::new(FakeLoader::default());796 let core = core_with(loader.clone());797 let (a, _thread) = fixture("a", 0);798 core.register(a).expect("register");799 core.residency().declare("cuda:0", 100);800 reserve_for(&core, "a", "cuda:0", 0);801 core.residency()802 .declare_intent("a", false, Some(Duration::from_millis(1)));803 thread::sleep(Duration::from_millis(5));804 805 // No caller supplies a clock or a busy set: the core reads both.806 assert_eq!(core.sweep_idle_now(), vec!["a".to_string()]);807 assert!(core.served("a").is_none());808 assert_eq!(loader.stops(), vec!["a".to_string()]);809 assert_eq!(core.residency().held("cuda:0"), 0);810 }811 812 #[test]813 fn a_no_room_refusal_stops_the_lru_plugin_and_the_retry_succeeds() {814 let loader = Arc::new(FakeLoader::default());815 let core = core_with(loader.clone());816 let (a, _thread_a) = fixture("a", 6);817 core.register(a).expect("register a");818 core.residency().declare("cuda:0", 10);819 reserve_for(&core, "a", "cuda:0", 6);820 821 let (b, _thread_b) = fixture("b", 6);822 core.register(b).expect("register b");823 824 let job = core825 .submit(submit("b", "chat", vec![text_part("hello")]))826 .expect("the retry admits");827 let (text, done) = drain(job);828 assert_eq!(text, "hello");829 assert_eq!(done.outcome, body::Outcome::Completed);830 831 assert_eq!(loader.stops(), vec!["a".to_string()]);832 assert!(core.served("a").is_none());833 assert_eq!(core.residency().held("cuda:0"), 6);834 835 release_all(&core, &["b"], "cuda:0");836 }837 838 #[test]839 fn an_evicted_model_reloads_on_the_next_request() {840 let loader = Arc::new(FakeLoader::default());841 let core = core_with(loader.clone());842 let (a, _thread_a) = fixture("a", 6);843 core.register(a).expect("register a");844 core.residency().declare("cuda:0", 10);845 reserve_for(&core, "a", "cuda:0", 6);846 847 let (b, _thread_b) = fixture("b", 6);848 core.register(b).expect("register b");849 let job = core850 .submit(submit("b", "chat", vec![text_part("b")]))851 .expect("b admits");852 let _ = drain(job);853 assert!(core.served("a").is_none());854 855 let job = core856 .submit(submit("a", "chat", vec![text_part("a")]))857 .expect("a reloads");858 let (text, done) = drain(job);859 assert_eq!(text, "a");860 assert_eq!(done.outcome, body::Outcome::Completed);861 assert_eq!(loader.starts.lock().unwrap().clone(), vec!["a".to_string()]);862 863 release_all(&core, &["a", "b"], "cuda:0");864 }865 866 #[test]867 fn a_host_with_only_a_pinned_resident_keeps_the_no_room_refusal() {868 let loader = Arc::new(FakeLoader::default());869 let core = core_with(loader.clone());870 let (a, _thread_a) = fixture("a", 6);871 core.register(a).expect("register a");872 core.residency().declare("cuda:0", 10);873 reserve_for(&core, "a", "cuda:0", 6);874 core.residency().declare_intent("a", true, None);875 876 let (b, _thread_b) = fixture("b", 6);877 core.register(b).expect("register b");878 879 let err = core880 .submit(submit("b", "chat", vec![text_part("hello")]))881 .unwrap_err();882 assert!(883 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::NoRoom),884 "{err:?}"885 );886 assert!(loader.stops().is_empty());887 assert!(core.served("a").is_some());888 assert_eq!(core.residency().held("cuda:0"), 6);889 890 release_all(&core, &["a"], "cuda:0");891 }892 893 #[test]894 fn a_switch_with_a_job_in_flight_is_busy() {895 let loader = Arc::new(FakeLoader::default());896 let core = core_with(loader.clone());897 let (a, _thread) = fixture("a", 0);898 core.register(a).expect("register a");899 900 let job = core901 .submit(submit("a", "chat", vec![text_part("held")]))902 .expect("submit");903 904 let err = core905 .switch("a", &["a".to_string()])906 .err()907 .expect("switch fails");908 assert!(err.to_string().contains("busy"), "{err}");909 assert!(core.served("a").is_some());910 assert!(loader.stops().is_empty());911 912 drop(job);913 release_all(&core, &["a"], "cuda:0");914 }915 916 #[test]917 fn a_stop_failure_keeps_the_old_plugin_registered() {918 let loader = Arc::new(FakeLoader::default());919 loader.fail_stop("a");920 let core = core_with(loader.clone());921 let (a, _thread) = fixture("a", 0);922 core.register(a).expect("register a");923 core.residency().declare("cuda:0", 10);924 reserve_for(&core, "a", "cuda:0", 0);925 926 let err = core927 .switch("a", &["a".to_string()])928 .err()929 .expect("switch fails");930 assert!(err.to_string().contains("stop_failed"), "{err}");931 assert!(core.served("a").is_some());932 assert!(core.residency().resident("a"));933 934 release_all(&core, &["a"], "cuda:0");935 }936 937 #[test]938 fn a_start_failure_leaves_the_ledger_free() {939 let loader = Arc::new(FakeLoader::default());940 loader.fail_start("a");941 let core = core_with(loader.clone());942 let (a, _thread) = fixture("a", 0);943 core.register(a).expect("register a");944 core.residency().declare("cuda:0", 10);945 reserve_for(&core, "a", "cuda:0", 0);946 947 let err = core948 .switch("a", &["a".to_string()])949 .err()950 .expect("switch fails");951 assert!(err.to_string().contains("start_failed"), "{err}");952 assert!(core.served("a").is_none());953 assert!(!core.residency().resident("a"));954 assert_eq!(core.residency().held("cuda:0"), 0);955 956 release_all(&core, &["a"], "cuda:0");957 }958 959 #[test]960 fn a_switch_whose_names_do_not_match_registers_nothing() {961 let loader = Arc::new(FakeLoader::default());962 let core = core_with(loader.clone());963 let (a, _thread) = fixture("a", 0);964 core.register(a).expect("register a");965 core.residency().declare("cuda:0", 10);966 reserve_for(&core, "a", "cuda:0", 0);967 968 let err = core969 .switch("a", &["b".to_string()])970 .err()971 .expect("switch fails");972 assert!(err.to_string().contains("mismatch"), "{err}");973 assert!(core.served("a").is_none());974 assert!(!core.residency().resident("a"));975 assert_eq!(core.residency().held("cuda:0"), 0);976 977 release_all(&core, &["a"], "cuda:0");978 }979 980 #[test]981 fn a_switch_registers_the_started_plugin_and_keeps_the_ledger_free() {982 let loader = Arc::new(FakeLoader::default());983 let core = core_with(loader.clone());984 let (a, _thread) = fixture("a", 0);985 core.register(a).expect("register a");986 core.residency().declare("cuda:0", 10);987 reserve_for(&core, "a", "cuda:0", 0);988 989 let served = core.switch("a", &["a".to_string()]).expect("switch");990 assert_eq!(served.plugin, "a");991 assert!(core.served("a").is_some());992 assert!(core.residency().resident("a"));993 assert_eq!(core.residency().held("cuda:0"), 0);994 995 release_all(&core, &["a"], "cuda:0");996 }997 998 #[test]999 fn engines_reports_a_row_per_plugin_with_its_counts_and_last_usage() {1000 let (alpha, alpha_thread) = fixture("alpha", 100);1001 let (beta, beta_thread) = fixture("beta", 250);1002 let core = Arc::new(Core::new());1003 core.register(alpha).expect("the alpha peer");1004 core.register(beta).expect("the beta peer");1005 1006 let held = core1007 .submit(submit("beta", "chat", vec![text_part("one")]))1008 .expect("the running job");1009 let (tx, rx) = mpsc::channel();1010 let waiting = Arc::clone(&core);1011 let queued_thread = thread::spawn(move || {1012 let job = waiting1013 .submit(submit("beta", "chat", vec![text_part("two")]))1014 .expect("the queued job");1015 let _ = tx.send(job);1016 });1017 1018 let deadline = Instant::now() + WAIT;1019 loop {1020 let queued = core1021 .engines()1022 .into_iter()1023 .find(|row| row.plugin == "beta")1024 .map(|row| row.queued)1025 .unwrap_or(0);1026 if queued == 1 {1027 break;1028 }1029 assert!(Instant::now() < deadline, "the second job never queued");1030 thread::sleep(Duration::from_millis(5));1031 }1032 1033 let rows = core.engines();1034 assert_eq!(rows.len(), 2);1035 assert_eq!(rows[0].plugin, "alpha");1036 assert_eq!(rows[0].served, vec!["alpha".to_string()]);1037 assert_eq!(rows[0].slots, 1);1038 assert_eq!(rows[0].in_flight, 0);1039 assert_eq!(rows[0].queued, 0);1040 assert_eq!(rows[0].load_ms, Some(1));1041 assert_eq!(rows[0].declared_bytes, 100);1042 assert_eq!(rows[0].measured_bytes, None);1043 assert_eq!(rows[0].tokens_out, None);1044 assert_eq!(rows[0].first_token_ms, None);1045 assert_eq!(rows[0].tokens_per_s, None);1046 1047 assert_eq!(rows[1].plugin, "beta");1048 assert_eq!(rows[1].served, vec!["beta".to_string()]);1049 assert_eq!(rows[1].slots, 1);1050 assert_eq!(rows[1].in_flight, 1);1051 assert_eq!(rows[1].queued, 1);1052 assert_eq!(rows[1].declared_bytes, 250);1053 assert_eq!(rows[1].tokens_out, None);1054 1055 drop(held);1056 let second = rx.recv_timeout(WAIT).expect("the queued job started");1057 let (_, done) = drain(second);1058 assert_eq!(done.outcome, body::Outcome::Completed);1059 1060 let rows = core.engines();1061 let beta = rows1062 .iter()1063 .find(|row| row.plugin == "beta")1064 .expect("the beta row");1065 assert_eq!(beta.tokens_out, Some(7));1066 assert_eq!(beta.first_token_ms, Some(12));1067 assert_eq!(beta.tokens_per_s, Some(345));1068 assert_eq!(beta.in_flight, 0);1069 assert_eq!(beta.queued, 0);1070 1071 queued_thread.join().expect("the waiting thread");1072 drop(core);1073 let _ = alpha_thread.join();1074 let _ = beta_thread.join();1075 }1076 1077 #[test]1078 fn a_crashed_plugin_fails_its_job_and_gives_the_bytes_back() {1079 let loader = Arc::new(FakeLoader::default());1080 let core = core_with(loader.clone());1081 // The fake device has no driver to settle, so the wait must not add two1082 // seconds to a test about the ledger, not about the driver.1083 core.residency().set_settle(Settle {1084 budget: Duration::ZERO,1085 step: Duration::from_millis(1),1086 });1087 let (a, _thread) = fixture("a", 0);1088 core.register(a).expect("register a");1089 core.residency().declare("cuda:0", 10);1090 reserve_for(&core, "a", "cuda:0", 4);1091 1092 let mut job = core1093 .submit(submit("a", "chat", vec![text_part("lost")]))1094 .expect("submit");1095 let id = job.id_str().to_string();1096 loader.exit_fails("a", SuperFailure::Killed);1097 1098 assert_eq!(core.reap(), vec!["a".to_string()]);1099 assert!(core.served("a").is_none());1100 assert_eq!(core.residency().held("cuda:0"), 0);1101 assert_eq!(loader.stops(), vec!["a".to_string()]);1102 // A frame that the reader queued before the socket ended may still be1103 // waiting. The stream must end, not necessarily at the first call.1104 loop {1105 match job.next() {1106 Ok(Some(_)) => continue,1107 Ok(None) => panic!("the dead stream ended without an error"),1108 Err(_) => break,1109 }1110 }1111 1112 let status = core.jobs().get(&id).expect("the job row");1113 assert!(1114 matches!(1115 status.state,1116 JobState::Failed {1117 code: RefusalCode::PluginCrashed,1118 ..1119 }1120 ),1121 "{status:?}"1122 );1123 }1124 1125 #[test]1126 fn a_permanent_failure_is_unloadable_until_a_switch() {1127 let loader = Arc::new(FakeLoader::default());1128 let core = core_with(loader.clone());1129 let (a, _thread) = fixture("a", 0);1130 core.register(a).expect("register a");1131 loader.exit_fails("a", SuperFailure::Frame);1132 1133 assert_eq!(core.reap(), vec!["a".to_string()]);1134 let err = core1135 .submit(submit("a", "chat", vec![text_part("blocked")]))1136 .unwrap_err();1137 assert!(1138 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::LoadFailed),1139 "{err:?}"1140 );1141 assert!(loader.starts.lock().unwrap().is_empty());1142 1143 // The operator reload is the one path that clears a permanent mark.1144 core.switch("a", &["a".to_string()]).expect("switch");1145 assert!(core.served("a").is_some());1146 let job = core1147 .submit(submit("a", "chat", vec![text_part("again")]))1148 .expect("the reload serves");1149 let (text, done) = drain(job);1150 assert_eq!(text, "again");1151 assert_eq!(done.outcome, body::Outcome::Completed);1152 }1153 1154 #[test]1155 fn a_permanent_start_failure_marks_the_plugin_unloadable() {1156 let loader = Arc::new(FakeLoader::default());1157 loader.fail_start_with("a", SuperFailure::Version);1158 let core = core_with(loader.clone());1159 let catalogue = Named {1160 name: "a".into(),1161 weights: 0,1162 context: 0,1163 kv: 0,1164 }1165 .catalogue();1166 core.register_cold("a", &catalogue, 1)1167 .expect("cold register");1168 1169 let err = core1170 .submit(submit("a", "chat", vec![text_part("once")]))1171 .unwrap_err();1172 assert!(1173 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::LoadFailed),1174 "{err:?}"1175 );1176 let err = core1177 .submit(submit("a", "chat", vec![text_part("again")]))1178 .unwrap_err();1179 assert!(1180 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::LoadFailed),1181 "{err:?}"1182 );1183 assert_eq!(loader.starts.lock().unwrap().len(), 1);1184 }1185 1186 #[test]1187 fn an_incompatible_plugin_is_a_version_failure() {1188 let (caller, serving) = UnixStream::pair().unwrap();1189 let server = thread::spawn(move || {1190 let (frame, _) = recv_frame(&serving).unwrap().expect("hello");1191 assert_eq!(frame.header.kind, Kind::Hello);1192 let body = Body::Welcome(Welcome {1193 v: 99,1194 max_inflight: 1,1195 });1196 let payload = body.encode();1197 let header = Header::new(Kind::Welcome, 0, payload.len() as u32);1198 send_frame(&serving, header, &payload, &[]).unwrap();1199 });1200 1201 let Err(err) = Served::connect("bad", caller, "bad", &[], WAIT) else {1202 panic!("version 99 must be refused")1203 };1204 assert_eq!(err.failure(), Some(SuperFailure::Version));1205 assert_eq!(err.code(), RefusalCode::Protocol);1206 server.join().unwrap();1207 }1208 1209 #[test]1210 fn wants_charge_only_the_bound_devices_and_include_the_kv_cache() {1211 let core = core_with(Arc::new(FakeLoader::default()));1212 let (a, _thread) = fixture_with("a", 100, 10, 2);1213 core.register(a).expect("register a");1214 core.set_devices("a", vec!["cuda:1".to_string()]);1215 core.residency().declare("cuda:0", 1_000);1216 core.residency().declare("cuda:1", 1_000);1217 1218 let job = core1219 .submit(submit("a", "chat", vec![text_part("kv")]))1220 .expect("the model fits");1221 let _ = drain(job);1222 // 100 weights + 10 tokens × 2 bytes, on cuda:1 only.1223 assert_eq!(core.residency().held("cuda:0"), 0);1224 assert_eq!(core.residency().held("cuda:1"), 120);1225 core.residency().release_all();1226 assert_eq!(core.residency().held("cuda:1"), 0);1227 }1228 1229 #[test]1230 fn a_no_room_refusal_evicts_until_the_new_model_fits() {1231 let loader = Arc::new(FakeLoader::default());1232 let core = core_with(loader.clone());1233 let (a, _thread_a) = fixture("a", 4);1234 core.register(a).expect("register a");1235 let (b, _thread_b) = fixture("b", 4);1236 core.register(b).expect("register b");1237 core.residency().declare("cuda:0", 10);1238 reserve_for(&core, "a", "cuda:0", 4);1239 core.residency().touch("b");1240 reserve_for(&core, "b", "cuda:0", 4);1241 core.residency().touch("a");1242 1243 let (c, _thread_c) = fixture("c", 9);1244 core.register(c).expect("register c");1245 let job = core1246 .submit(submit("c", "chat", vec![text_part("both")]))1247 .expect("two victims make room");1248 let _ = drain(job);1249 1250 assert_eq!(loader.stops(), vec!["b".to_string(), "a".to_string()]);1251 assert_eq!(core.residency().held("cuda:0"), 9);1252 assert!(core.served("a").is_none());1253 assert!(core.served("b").is_none());1254 core.residency().release_all();1255 assert_eq!(core.residency().held("cuda:0"), 0);1256 }1257 1258 #[test]1259 fn a_job_that_stops_answering_expires_at_its_deadline() {1260 let (caller, serving) = UnixStream::pair().unwrap();1261 let stop = Arc::new(AtomicBool::new(false));1262 let plugin = Hang {1263 stop: Arc::clone(&stop),1264 };1265 let _thread = thread::spawn(move || serve(serving, Arc::new(plugin)));1266 let peer = Served::connect("hang", caller, "hang", &[], WAIT).expect("connect");1267 let core = Core::new();1268 core.register(peer).expect("register");1269 1270 let mut request = submit("hang", "chat", vec![text_part("wait")]);1271 request.budget = Duration::from_millis(500);1272 let mut job = core.submit(request).expect("submit");1273 let id = job.id_str().to_string();1274 match job.next() {1275 Ok(Some(Item::Accepted(_))) => {}1276 Ok(Some(other)) => panic!("unexpected {other:?}"),1277 Ok(None) => panic!("the job ended before the deadline"),1278 Err(why) => panic!("the job failed before the deadline: {why}"),1279 }1280 1281 let started = Instant::now();1282 let Err(why) = job.next() else {1283 panic!("a hung job must not deliver a frame after its deadline")1284 };1285 assert_eq!(why.kind(), std::io::ErrorKind::TimedOut);1286 assert!(started.elapsed() < Duration::from_secs(2));1287 assert!(core.served("hang").is_none());1288 let status = core.jobs().get(&id).expect("the row");1289 assert!(1290 matches!(1291 status.state,1292 JobState::Failed {1293 code: RefusalCode::Timeout,1294 ..1295 }1296 ),1297 "{status:?}"1298 );1299 stop.store(true, Ordering::SeqCst);1300 }1301 1302 #[test]1303 fn a_bounded_wait_is_idle_and_leaves_the_job_running() {1304 let (caller, serving) = UnixStream::pair().unwrap();1305 let stop = Arc::new(AtomicBool::new(false));1306 let plugin = Hang {1307 stop: Arc::clone(&stop),1308 };1309 let _thread = thread::spawn(move || serve(serving, Arc::new(plugin)));1310 let peer = Served::connect("hang", caller, "hang", &[], WAIT).expect("connect");1311 let core = Core::new();1312 core.register(peer).expect("register");1313 1314 let mut job = core1315 .submit(submit("hang", "chat", vec![text_part("wait")]))1316 .expect("submit");1317 let id = job.id_str().to_string();1318 match job.next() {1319 Ok(Some(Item::Accepted(_))) => {}1320 Ok(Some(other)) => panic!("unexpected {other:?}"),1321 Ok(None) => panic!("the job ended before the wait"),1322 Err(why) => panic!("the job failed before the wait: {why}"),1323 }1324 1325 let started = Instant::now();1326 match job.wait(Duration::from_millis(50)).expect("wait") {1327 Wait::Idle => {}1328 Wait::Item(other) => panic!("the wait returned {other:?}"),1329 }1330 assert!(started.elapsed() < Duration::from_secs(2));1331 let status = core.jobs().get(&id).expect("the row");1332 assert_eq!(1333 status.state,1334 JobState::Running,1335 "a short wait ended the job"1336 );1337 1338 stop.store(true, Ordering::SeqCst);1339 match job.wait(WAIT).expect("wait for the plugin") {1340 Wait::Item(Some(Item::Done(..))) => {}1341 Wait::Item(other) => panic!("unexpected {other:?}"),1342 Wait::Idle => panic!("the plugin finished but the wait was idle"),1343 }1344 }1345 1346 #[test]1347 fn two_names_of_one_plugin_share_one_slot() {1348 let (caller, serving) = UnixStream::pair().unwrap();1349 let plugin = Aliased;1350 let _thread = thread::spawn(move || serve(serving, Arc::new(plugin)));1351 let peer = Served::connect("pair", caller, "pair", &[], WAIT).expect("connect");1352 let core = Core::new();1353 core.register(peer).expect("register");1354 core.finish_catalog().expect("the alias resolves");1355 1356 let held = core1357 .submit(submit("base", "chat", vec![text_part("one")]))1358 .expect("the first job");1359 let mut second = submit("alias", "chat", vec![text_part("two")]);1360 second.budget = Duration::from_millis(250);1361 let started = Instant::now();1362 let err = core.submit(second).unwrap_err();1363 assert!(1364 matches!(err, CoreError::Refused(ref refusal) if refusal.code == RefusalCode::Timeout),1365 "{err:?}"1366 );1367 assert!(started.elapsed() >= Duration::from_millis(250));1368 assert_eq!(core.sched().in_flight("pair"), 1);1369 assert_eq!(core.sched().queued("pair"), 0);1370 1371 drop(held);1372 }1373 1374 #[test]1375 fn an_abandoned_job_is_recorded_as_cancelled() {1376 let (core, _served) = core();1377 let job = core1378 .submit(submit("echo", "chat", vec![text_part("leave")]))1379 .expect("submit");1380 let id = job.id_str().to_string();1381 drop(job);1382 let status = core.jobs().get(&id).expect("the row");1383 assert_eq!(1384 status.state,1385 JobState::Done {1386 outcome: "cancelled".to_string()1387 }1388 );1389 }