1 //! The ledger of device bytes, seen from the core.2 //!3 //! A device is declared once. A model reserves the bytes that its bind says, and4 //! a second model that does not fit is refused instead of started.5 6 use std::collections::{BTreeMap, BTreeSet};7 use std::sync::Mutex;8 use std::time::{Duration, Instant};9 10 use inf3r_core::{Memory, Residency, ResidencyError, Settle, Waiter};11 use inf3r_host::process_tree;12 13 fn wants(pairs: &[(&str, u64)]) -> BTreeMap<String, u64> {14 pairs15 .iter()16 .map(|(device, bytes)| (device.to_string(), *bytes))17 .collect()18 }19 20 #[test]21 fn a_declared_device_holds_its_bytes() {22 let residency = Residency::new();23 residency.declare("cuda:0", 12_000);24 assert_eq!(residency.total("cuda:0"), Some(12_000));25 assert_eq!(residency.held("cuda:0"), 0);26 }27 28 #[test]29 fn the_first_declaration_wins() {30 let residency = Residency::new();31 residency.declare("cuda:0", 12_000);32 residency.declare("cuda:0", 24_000);33 assert_eq!(residency.total("cuda:0"), Some(12_000));34 }35 36 #[test]37 fn a_fitting_model_is_resident_and_a_second_one_is_refused() {38 let residency = Residency::new();39 residency.declare("cuda:0", 12_000);40 let first = residency41 .reserve(&wants(&[("cuda:0", 9_000)]))42 .expect("fits");43 assert_eq!(residency.held("cuda:0"), 9_000);44 45 let err = residency46 .reserve(&wants(&[("cuda:0", 4_000)]))47 .expect_err("does not fit");48 assert!(49 matches!(err, ResidencyError::NoRoom { ref device, .. } if device == "cuda:0"),50 "{err:?}"51 );52 53 residency.release(first);54 assert_eq!(residency.held("cuda:0"), 0);55 }56 57 #[test]58 fn a_model_that_needs_two_devices_gets_both_or_neither() {59 let residency = Residency::new();60 residency.declare("cuda:0", 12_000);61 residency.declare("cuda:1", 4_000);62 63 let err = residency64 .reserve(&wants(&[("cuda:0", 6_000), ("cuda:1", 6_000)]))65 .expect_err("one device is short");66 assert!(matches!(err, ResidencyError::NoRoom { .. }));67 // All or nothing: the device that had room must not stay reserved.68 assert_eq!(residency.held("cuda:0"), 0);69 }70 71 #[test]72 fn an_undeclared_device_is_unknown() {73 let residency = Residency::new();74 residency.declare("cuda:0", 12_000);75 let err = residency76 .reserve(&wants(&[("cuda:9", 1)]))77 .expect_err("undeclared");78 assert!(matches!(err, ResidencyError::Unknown { ref device } if device == "cuda:9"));79 assert_eq!(err.code(), inf3r_core::RefusalCode::Mismatch);80 }81 82 #[test]83 fn the_device_list_names_bytes_total_and_used() {84 let residency = Residency::new();85 residency.declare("cuda:0", 12_000);86 let held = residency87 .reserve(&wants(&[("cuda:0", 3_000)]))88 .expect("fits");89 assert_eq!(90 residency.devices(),91 vec![("cuda:0".to_string(), 12_000, 3_000)]92 );93 residency.release(held);94 }95 96 /// A clock that reports zero for a few samples and then the wanted number.97 struct Rising {98 want: u64,99 zeros: u32,100 seen: u32,101 slept: Duration,102 }103 104 impl Waiter for Rising {105 fn sample(&mut self, _device: &str) -> Option<u64> {106 let free = if self.seen < self.zeros { 0 } else { self.want };107 self.seen += 1;108 Some(free)109 }110 111 fn sleep(&mut self, d: Duration) {112 self.slept += d;113 }114 }115 116 /// A device that never frees a byte.117 struct Stuck {118 slept: Duration,119 }120 121 impl Waiter for Stuck {122 fn sample(&mut self, _device: &str) -> Option<u64> {123 Some(0)124 }125 126 fn sleep(&mut self, d: Duration) {127 self.slept += d;128 }129 }130 131 fn settle_clock() -> Settle {132 Settle {133 budget: Duration::from_secs(1),134 step: Duration::from_millis(100),135 }136 }137 138 #[test]139 fn settle_returns_after_the_device_reports_the_bytes() {140 let residency = Residency::with_settle(settle_clock());141 residency.declare("cuda:0", 10_000);142 let mut waiter = Rising {143 want: 4_000,144 zeros: 3,145 seen: 0,146 slept: Duration::ZERO,147 };148 let waited = residency149 .settle("cuda:0", 4_000, &mut waiter)150 .expect("the device frees the bytes");151 assert_eq!(waited, Duration::from_millis(300));152 assert_eq!(waiter.slept, Duration::from_millis(300));153 assert_eq!(waiter.seen, 4);154 }155 156 #[test]157 fn a_device_that_never_frees_reports_the_three_numbers() {158 let residency = Residency::with_settle(settle_clock());159 residency.declare("cuda:0", 10_000);160 let mut waiter = Stuck {161 slept: Duration::ZERO,162 };163 let err = residency164 .settle("cuda:0", 4_000, &mut waiter)165 .expect_err("the device stays full");166 match &err {167 ResidencyError::Settled {168 device,169 want,170 free,171 waited,172 } => {173 assert_eq!(device, "cuda:0");174 assert_eq!(*want, 4_000);175 assert_eq!(*free, 0);176 assert_eq!(*waited, Duration::from_secs(1));177 }178 other => panic!("expected Settled, got {other:?}"),179 }180 assert_eq!(waiter.slept, Duration::from_secs(1));181 let message = err.to_string();182 assert!(message.contains("4000"), "{message}");183 assert!(message.contains("0 bytes"), "{message}");184 assert!(message.contains("1s"), "{message}");185 }186 187 /// One tebibyte, a declaration that no child on this host can hold.188 const TERABYTE: u64 = 1 << 40;189 190 /// A child that stays alive while the test measures it.191 struct Sleeper(std::process::Child);192 193 impl Sleeper {194 fn start() -> Sleeper {195 // Keep the shell alive as the parent of the sleep, so the tree has196 // two processes and the test measures a bound-bundle shape.197 let child = std::process::Command::new("sh")198 .args(["-c", "sleep 5 & wait"])199 .spawn()200 .expect("spawn a sleeper");201 Sleeper(child)202 }203 }204 205 impl Drop for Sleeper {206 fn drop(&mut self) {207 let _ = self.0.kill();208 let _ = self.0.wait();209 }210 }211 212 #[test]213 fn a_child_that_holds_less_than_it_declared_is_short() {214 let residency = Residency::new();215 let sleeper = Sleeper::start();216 let pid = sleeper.0.id();217 let err = residency218 .verify_bytes(pid, TERABYTE)219 .expect_err("no child holds a tebibyte");220 match &err {221 ResidencyError::Short {222 declared,223 measured,224 pid: reported,225 } => {226 assert_eq!(*declared, TERABYTE);227 assert!(*measured > 0);228 assert!(*measured < TERABYTE);229 assert_eq!(*reported, pid);230 }231 other => panic!("expected Short, got {other:?}"),232 }233 let message = err.to_string();234 assert!(message.contains(&pid.to_string()), "{message}");235 assert!(message.contains(&TERABYTE.to_string()), "{message}");236 }237 238 #[test]239 fn a_zero_declaration_passes() {240 let residency = Residency::new();241 let sleeper = Sleeper::start();242 residency243 .verify_bytes(sleeper.0.id(), 0)244 .expect("the mock declares no weights");245 }246 247 fn busy(names: &[&str]) -> BTreeSet<String> {248 names.iter().map(|name| name.to_string()).collect()249 }250 251 fn hold(residency: &Residency, plugin: &str) {252 let reservation = residency253 .reserve(&wants(&[("cuda:0", 1)]))254 .expect("one byte fits");255 residency.hold(plugin, reservation);256 }257 258 #[test]259 fn idle_candidates_are_oldest_first_and_skip_a_pin_or_a_job() {260 let residency = Residency::new();261 residency.declare("cuda:0", 100);262 for plugin in ["a", "b", "c", "d"] {263 hold(&residency, plugin);264 residency.declare_intent(plugin, false, Some(Duration::from_millis(1)));265 }266 residency.declare_intent("c", true, Some(Duration::from_millis(1)));267 268 residency.touch("b");269 std::thread::sleep(Duration::from_millis(2));270 residency.touch("a");271 std::thread::sleep(Duration::from_millis(2));272 residency.touch("c");273 std::thread::sleep(Duration::from_millis(2));274 residency.touch("d");275 276 let now = Instant::now() + Duration::from_secs(1);277 assert_eq!(278 residency.idle_candidates(now, &busy(&["a"])),279 vec!["b".to_string(), "d".to_string()]280 );281 282 for plugin in ["a", "b", "c", "d"] {283 if let Some(reservation) = residency.release_plugin(plugin) {284 residency.release(reservation);285 }286 }287 assert_eq!(residency.held("cuda:0"), 0);288 }289 290 #[test]291 fn lru_skips_a_pin_and_a_plugin_with_a_job() {292 let residency = Residency::new();293 residency.declare("cuda:0", 100);294 for plugin in ["a", "b", "c"] {295 hold(&residency, plugin);296 }297 residency.declare_intent("c", true, None);298 299 residency.touch("b");300 std::thread::sleep(Duration::from_millis(2));301 residency.touch("a");302 std::thread::sleep(Duration::from_millis(2));303 residency.touch("c");304 305 assert_eq!(residency.lru(&busy(&[])), Some("b".to_string()));306 assert_eq!(residency.lru(&busy(&["b"])), Some("a".to_string()));307 assert_eq!(residency.lru(&busy(&["a", "b"])), None);308 309 for plugin in ["a", "b", "c"] {310 if let Some(reservation) = residency.release_plugin(plugin) {311 residency.release(reservation);312 }313 }314 assert_eq!(residency.held("cuda:0"), 0);315 }316 317 #[test]318 fn declaring_a_second_device_keeps_the_first_reservation() {319 let residency = Residency::new();320 residency.declare("cuda:0", 10_000);321 let held = residency322 .reserve(&wants(&[("cuda:0", 4_000)]))323 .expect("the first device has room");324 325 residency.declare("cuda:1", 20_000);326 assert_eq!(residency.total("cuda:1"), Some(20_000));327 assert_eq!(residency.held("cuda:0"), 4_000);328 assert_eq!(residency.held("cuda:1"), 0);329 330 residency.release(held);331 }332 333 #[test]334 fn a_settle_target_is_what_the_device_has_after_the_release() {335 let residency = Residency::new();336 residency.declare("cuda:0", 10_000);337 let one = residency338 .reserve(&wants(&[("cuda:0", 3_000)]))339 .expect("one");340 let two = residency341 .reserve(&wants(&[("cuda:0", 2_000)]))342 .expect("two");343 344 // Total 10000, held 5000. Releasing the 2000 reservation leaves 3000345 // held, so the driver must report 7000 free before the release is safe.346 assert_eq!(residency.free_after("cuda:0", 2_000), Some(7_000));347 assert_eq!(residency.free_after("cuda:0", 3_000), Some(8_000));348 assert_eq!(residency.free_after("cuda:9", 1), None);349 350 residency.release(one);351 residency.release(two);352 }353 354 #[derive(Default)]355 struct FakeMemory {356 rss: Option<u64>,357 vram: BTreeMap<String, u64>,358 rss_seen: Mutex<Vec<u32>>,359 vram_seen: Mutex<Vec<String>>,360 }361 362 impl Memory for FakeMemory {363 fn rss(&self, root: u32) -> Option<u64> {364 self.rss_seen.lock().unwrap().push(root);365 self.rss366 }367 368 fn vram(&self, root: u32, device: &str) -> Option<u64> {369 assert_eq!(root, std::process::id());370 self.vram_seen.lock().unwrap().push(device.to_string());371 self.vram.get(device).copied()372 }373 }374 375 #[test]376 fn a_gpu_load_is_measured_in_device_memory_not_host_rss() {377 let residency = Residency::new();378 let fake = FakeMemory {379 rss: Some(1_000_000),380 vram: BTreeMap::from([("cuda:0".into(), 30), ("cuda:1".into(), 40)]),381 ..FakeMemory::default()382 };383 384 let measured = residency385 .verify_devices(386 std::process::id(),387 100,388 &["cuda:0".into(), "cuda:1".into()],389 &fake,390 )391 .expect("the two devices hold seventy bytes");392 assert_eq!(measured, Some(70));393 assert!(fake.rss_seen.lock().unwrap().is_empty());394 assert_eq!(395 fake.vram_seen.lock().unwrap().clone(),396 vec!["cuda:0".to_string(), "cuda:1".to_string()]397 );398 }399 400 #[test]401 fn a_cpu_load_is_measured_in_the_process_tree() {402 let residency = Residency::new();403 let sleeper = Sleeper::start();404 let started = Instant::now();405 while process_tree(sleeper.0.id()).len() < 2 && started.elapsed() < Duration::from_secs(2) {406 std::thread::sleep(Duration::from_millis(10));407 }408 let fake = FakeMemory {409 rss: Some(60),410 ..FakeMemory::default()411 };412 413 let measured = residency414 .verify_devices(sleeper.0.id(), 100, &["cpu:0".into()], &fake)415 .expect("the tree holds sixty bytes");416 assert_eq!(measured, Some(60));417 assert!(fake.vram_seen.lock().unwrap().is_empty());418 let seen = fake.rss_seen.lock().unwrap();419 assert_eq!(seen[0], sleeper.0.id());420 }421 422 #[test]423 fn a_gpu_load_that_holds_less_than_half_is_short() {424 let residency = Residency::new();425 let fake = FakeMemory {426 vram: BTreeMap::from([("cuda:0".into(), 40)]),427 ..FakeMemory::default()428 };429 let err = residency430 .verify_devices(std::process::id(), 100, &["cuda:0".into()], &fake)431 .expect_err("forty is less than half of one hundred");432 assert!(matches!(err, ResidencyError::Short { measured: 40, .. }));433 }434 435 #[test]436 fn a_container_free_sampler_replaces_the_local_probe() {437 let residency = Residency::new();438 residency.declare("cuda:0", 10_000);439 residency.set_free_sampler(|device| (device == "cuda:0").then_some(7_500));440 residency.capture_free_on("plugin", &["cuda:0".to_string()]);441 assert_eq!(442 residency.stop_target("plugin", "cuda:0", 2_500),443 Some(7_500)444 );445 residency.set_free_sampler(|_device| Some(10_000));446 assert_eq!(447 residency448 .settle_default("cuda:0", 10_000)449 .expect("the probe reports the line"),450 Duration::ZERO451 );452 }453 454 #[test]455 fn the_lru_victim_is_chosen_from_the_short_device() {456 let residency = Residency::new();457 residency.declare("cpu:0", 8_000);458 residency.declare("cuda:0", 8_000);459 let cpu = residency460 .reserve(&wants(&[("cpu:0", 2_000)]))461 .expect("cpu fits");462 residency.hold("cpu", cpu);463 let gpu = residency464 .reserve(&wants(&[("cuda:0", 6_000)]))465 .expect("gpu fits");466 residency.hold("gpu", gpu);467 468 let empty = BTreeSet::new();469 assert_eq!(470 residency.lru_on("cuda:0", &empty, &empty).as_deref(),471 Some("gpu")472 );473 assert_eq!(474 residency.lru_on("cpu:0", &empty, &empty).as_deref(),475 Some("cpu")476 );477 478 for plugin in ["gpu", "cpu"] {479 let reservation = residency480 .release_plugin(plugin)481 .expect("the test held this reservation");482 residency.release(reservation);483 }484 }