1 //! The cache is a resource, so the tests serialise on one manager. Every test2 //! opens a real tier under a temp directory; the per-filesystem authority means3 //! two live managers cannot overlap even in a test.4 5 use std::collections::BTreeMap;6 use std::fs;7 use std::io::{Read, Seek, SeekFrom, Write};8 use std::os::fd::AsRawFd;9 use std::os::unix::fs::PermissionsExt;10 use std::path::{Path, PathBuf};11 use std::sync::{Mutex, MutexGuard};12 use std::time::{Duration, SystemTime, UNIX_EPOCH};13 14 use inf3r_cache::{15 Cache, CacheConfig, CacheSpec, EntryKind, Persist, StateKind, TierConfig, class_ttl, entry_id,16 };17 18 static ONE: Mutex<()> = Mutex::new(());19 20 fn one() -> MutexGuard<'static, ()> {21 ONE.lock().unwrap_or_else(|poisoned| poisoned.into_inner())22 }23 24 fn now() -> u64 {25 SystemTime::now()26 .duration_since(UNIX_EPOCH)27 .unwrap()28 .as_millis() as u6429 }30 31 fn temp(name: &str) -> PathBuf {32 let dir = std::env::temp_dir().join(format!(33 "inf3r-cache-test-{name}-{}-{}",34 std::process::id(),35 now()36 ));37 let _ = fs::remove_dir_all(&dir);38 fs::create_dir_all(&dir).unwrap();39 fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();40 dir41 }42 43 fn config(dir: &Path, bound: u64) -> CacheConfig {44 CacheConfig {45 enabled: true,46 persist: Persist::Reboot,47 pin_bound: bound / 2,48 flush_budget: Duration::from_secs(1),49 default_ttl: Duration::from_secs(3600),50 classes: [("standard".to_string(), Duration::from_secs(3600))]51 .into_iter()52 .collect(),53 tiers: vec![TierConfig {54 name: "tier".into(),55 dir: dir.to_path_buf(),56 bound: Some(bound),57 headroom: 0,58 ttl: None,59 }],60 blob_dir: PathBuf::new(),61 }62 }63 64 fn spec(max: u64) -> CacheSpec {65 CacheSpec {66 codec_version: 1,67 slots: 1,68 state_kind: StateKind::CheckpointExact,69 max_entry_bytes: max,70 local_ram_bytes: 0,71 supports_save: true,72 supports_restore: true,73 supports_erase: true,74 }75 }76 77 fn key(n: u8) -> [u8; 32] {78 [n; 32]79 }80 81 fn fp(n: u8) -> [u8; 32] {82 [n; 32]83 }84 85 fn open(cache: &Cache, session: u64, fingerprint: [u8; 32]) {86 cache87 .open_session(88 session,89 "test/1x0",90 fingerprint,91 spec(1024 * 1024),92 Duration::from_secs(3600),93 )94 .unwrap();95 }96 97 #[test]98 fn commit_lookup_restore_and_release() {99 let _one = one();100 let dir = temp("roundtrip");101 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();102 open(&cache, 1, fp(1));103 let payload = b"opaque kv bytes";104 let lease = cache105 .reserve(106 1,107 key(1),108 None,109 None,110 EntryKind::Tip,111 payload.len() as u64,112 100,113 3,114 false,115 )116 .unwrap();117 let lease_id = lease.lease_id();118 {119 let mut file = lease.file().try_clone().unwrap();120 file.write_all(payload).unwrap();121 file.sync_all().unwrap();122 }123 let crc = inf3r_cache::crc32c(payload);124 let meta = cache125 .commit(1, lease_id, payload.len() as u64, crc, 3, 7)126 .unwrap();127 assert_eq!(meta.bytes, payload.len() as u64);128 assert_eq!(meta.token_count, 3);129 drop(lease);130 assert_eq!(cache.len(), 1);131 assert_eq!(cache.entries()[0].id, entry_id(fp(1), &key(1)));132 133 let hit = cache.lookup(1, &[key(1)], None).unwrap().expect("hit");134 assert_eq!(hit.key, key(1));135 let mut file = hit.file().try_clone().unwrap();136 let mut got = Vec::new();137 file.read_to_end(&mut got).unwrap();138 assert_eq!(got, payload);139 hit.release(true);140 assert_eq!(cache.stats().hits, 1);141 assert_eq!(cache.stats().misses, 0);142 143 let miss = cache.lookup(1, &[key(9)], None).unwrap();144 assert!(miss.is_none());145 assert_eq!(cache.stats().misses, 1);146 }147 148 #[test]149 fn a_corrupt_crc_never_publishes() {150 let _one = one();151 let dir = temp("crc");152 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();153 open(&cache, 1, fp(1));154 let payload = b"one payload";155 let lease = cache156 .reserve(1, key(1), None, None, EntryKind::Tip, 11, 100, 1, false)157 .unwrap();158 let id = lease.lease_id();159 lease160 .file()161 .try_clone()162 .unwrap()163 .write_all(payload)164 .unwrap();165 let err = cache.commit(1, id, 11, 0, 1, 1).unwrap_err();166 assert!(matches!(err, inf3r_cache::CacheError::Corrupt(_)));167 drop(lease);168 assert_eq!(cache.len(), 0);169 assert!(cache.entry_path(&entry_id(fp(1), &key(1))).is_none());170 }171 172 #[test]173 fn abort_and_peer_crash_remove_temps() {174 let _one = one();175 let dir = temp("abort");176 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();177 open(&cache, 1, fp(1));178 let lease = cache179 .reserve(1, key(1), None, None, EntryKind::Tip, 4, 100, 1, false)180 .unwrap();181 let id = lease.lease_id();182 lease183 .file()184 .try_clone()185 .unwrap()186 .write_all(b"temp")187 .unwrap();188 cache.abort(1, id);189 drop(lease);190 assert_eq!(cache.len(), 0);191 assert!(fs::read_dir(dir.join(".tmp")).unwrap().next().is_none());192 193 let lease = cache194 .reserve(1, key(2), None, None, EntryKind::Tip, 4, 100, 1, false)195 .unwrap();196 lease197 .file()198 .try_clone()199 .unwrap()200 .write_all(b"temp")201 .unwrap();202 cache.abort_peer(1);203 drop(lease);204 assert!(fs::read_dir(dir.join(".tmp")).unwrap().next().is_none());205 }206 207 #[test]208 fn supersession_keeps_one_tip() {209 let _one = one();210 let dir = temp("supersede");211 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();212 open(&cache, 1, fp(1));213 for turn in 1..=3u8 {214 let payload = vec![turn; 128];215 let lease = cache216 .reserve(217 1,218 key(turn),219 None,220 (turn > 1).then(|| key(turn - 1)),221 EntryKind::Tip,222 128,223 100,224 1,225 false,226 )227 .unwrap();228 let id = lease.lease_id();229 lease230 .file()231 .try_clone()232 .unwrap()233 .write_all(&payload)234 .unwrap();235 cache236 .commit(1, id, 128, inf3r_cache::crc32c(&payload), 1, 1)237 .unwrap();238 }239 assert_eq!(cache.len(), 1);240 assert_eq!(cache.entries()[0].key, key(3));241 }242 243 #[test]244 fn a_shared_prefix_becomes_an_anchor() {245 let _one = one();246 let dir = temp("anchor");247 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();248 open(&cache, 1, fp(1));249 let lease = cache250 .reserve(251 1,252 key(1),253 Some(key(9)),254 None,255 EntryKind::Tip,256 8,257 100,258 1,259 false,260 )261 .unwrap();262 let id = lease.lease_id();263 lease264 .file()265 .try_clone()266 .unwrap()267 .write_all(b"anchor!!")268 .unwrap();269 cache270 .commit(1, id, 8, inf3r_cache::crc32c(b"anchor!!"), 1, 1)271 .unwrap();272 // The first hit has one lineage. A second hit with a different lineage273 // promotes it; the entry then survives a superseding tip.274 let first = cache.lookup(1, &[key(1)], Some(key(9))).unwrap().unwrap();275 first.release(true);276 let second = cache.lookup(1, &[key(1)], Some(key(8))).unwrap().unwrap();277 second.release(true);278 let meta = cache279 .entries()280 .into_iter()281 .find(|m| m.key == key(1))282 .unwrap();283 assert!(meta.anchor);284 }285 286 #[test]287 fn restart_recovers_committed_entries_and_tolerates_a_torn_tail() {288 let _one = one();289 let dir = temp("restart");290 {291 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();292 open(&cache, 1, fp(1));293 let payload = b"persisted";294 let lease = cache295 .reserve(1, key(1), None, None, EntryKind::Tip, 9, 100, 1, false)296 .unwrap();297 let id = lease.lease_id();298 lease299 .file()300 .try_clone()301 .unwrap()302 .write_all(payload)303 .unwrap();304 cache305 .commit(1, id, 9, inf3r_cache::crc32c(payload), 1, 1)306 .unwrap();307 }308 let log = dir.join("index.log");309 let mut bytes = fs::read(&log).unwrap();310 bytes.extend_from_slice(&[0xff, 0x00, 0x01]);311 fs::write(&log, bytes).unwrap();312 313 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();314 open(&cache, 1, fp(1));315 assert_eq!(cache.len(), 1);316 let hit = cache.lookup(1, &[key(1)], None).unwrap().unwrap();317 hit.release(true);318 // A fresh root has no snapshot, so recovery truncates the torn tail to319 // the last valid record instead of replaying a half-written one.320 let recovered = fs::metadata(log).unwrap().len();321 assert!(recovered > 0 && recovered < 400);322 }323 324 #[test]325 fn ttl_expires_on_lookup() {326 let _one = one();327 let dir = temp("ttl");328 let mut cfg = config(&dir, 1024 * 1024);329 cfg.default_ttl = Duration::from_millis(1);330 let cache = Cache::open(cfg).unwrap();331 cache332 .open_session(333 1,334 "test/1x0",335 fp(1),336 spec(1024 * 1024),337 Duration::from_millis(1),338 )339 .unwrap();340 let payload = b"short";341 let lease = cache342 .reserve(1, key(1), None, None, EntryKind::Tip, 5, 100, 1, false)343 .unwrap();344 let id = lease.lease_id();345 lease346 .file()347 .try_clone()348 .unwrap()349 .write_all(payload)350 .unwrap();351 cache352 .commit(1, id, 5, inf3r_cache::crc32c(payload), 1, 1)353 .unwrap();354 std::thread::sleep(Duration::from_millis(5));355 assert!(cache.lookup(1, &[key(1)], None).unwrap().is_none());356 assert_eq!(cache.len(), 0);357 }358 359 #[test]360 fn a_second_manager_cannot_claim_the_same_filesystem() {361 let _one = one();362 let dir = temp("authority");363 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();364 let err = Cache::open(config(&dir, 1024 * 1024)).unwrap_err();365 assert!(matches!(err, inf3r_cache::CacheError::Busy(_)));366 drop(cache);367 }368 369 #[test]370 fn disabled_cache_refuses_operations() {371 let _one = one();372 let config = CacheConfig::default();373 let cache = Cache::open(config).unwrap();374 assert!(!cache.enabled());375 assert!(matches!(376 cache.lookup(1, &[key(1)], None),377 Err(inf3r_cache::CacheError::Disabled)378 ));379 }380 381 #[test]382 fn session_persist_wipes_entries() {383 let _one = one();384 let dir = temp("session");385 {386 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();387 open(&cache, 1, fp(1));388 let lease = cache389 .reserve(1, key(1), None, None, EntryKind::Tip, 4, 100, 1, false)390 .unwrap();391 let id = lease.lease_id();392 lease393 .file()394 .try_clone()395 .unwrap()396 .write_all(b"wipe")397 .unwrap();398 cache399 .commit(1, id, 4, inf3r_cache::crc32c(b"wipe"), 1, 1)400 .unwrap();401 }402 let mut cfg = config(&dir, 1024 * 1024);403 cfg.persist = Persist::Session;404 let cache = Cache::open(cfg).unwrap();405 assert_eq!(cache.len(), 0);406 }407 408 #[test]409 fn class_ttl_is_host_policy() {410 let cfg = config(Path::new("/nonexistent"), 100);411 assert_eq!(class_ttl(&cfg, "standard"), Duration::from_secs(3600));412 assert_eq!(class_ttl(&cfg, "missing"), cfg.default_ttl);413 }414 415 #[test]416 fn fd_and_crc_helpers_are_consistent() {417 let _one = one();418 let dir = temp("fd");419 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();420 open(&cache, 1, fp(1));421 let payload: Vec<u8> = (0..1024).map(|n| n as u8).collect();422 let lease = cache423 .reserve(1, key(1), None, None, EntryKind::Tip, 1024, 100, 1, false)424 .unwrap();425 let id = lease.lease_id();426 let mut file = lease.file().try_clone().unwrap();427 file.write_all(&payload).unwrap();428 file.seek(SeekFrom::Start(0)).unwrap();429 let mut back = Vec::new();430 file.read_to_end(&mut back).unwrap();431 assert!(lease.as_fd().as_raw_fd() >= 0);432 cache433 .commit(1, id, 1024, inf3r_cache::crc32c(&payload), 1, 1)434 .unwrap();435 }436 437 #[test]438 fn a_snapshot_survives_a_restart_and_compaction() {439 let _one = one();440 let dir = temp("compact");441 {442 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();443 open(&cache, 1, fp(1));444 let payload = b"snapshot";445 let lease = cache446 .reserve(1, key(1), None, None, EntryKind::Tip, 8, 100, 1, false)447 .unwrap();448 let id = lease.lease_id();449 lease450 .file()451 .try_clone()452 .unwrap()453 .write_all(payload)454 .unwrap();455 cache456 .commit(1, id, 8, inf3r_cache::crc32c(payload), 1, 1)457 .unwrap();458 cache.compact().unwrap();459 assert!(dir.join("index.snap").is_file());460 }461 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();462 open(&cache, 1, fp(1));463 assert_eq!(cache.len(), 1);464 let hit = cache.lookup(1, &[key(1)], None).unwrap().unwrap();465 hit.release(true);466 }467 468 #[test]469 fn a_pin_over_the_bound_is_refused_without_writing() {470 let _one = one();471 let dir = temp("pin");472 let mut cfg = config(&dir, 1024 * 1024);473 cfg.pin_bound = 4;474 let cache = Cache::open(cfg).unwrap();475 open(&cache, 1, fp(1));476 let err = cache477 .reserve(1, key(1), None, None, EntryKind::Tip, 8, 100, 1, true)478 .unwrap_err();479 assert!(matches!(err, inf3r_cache::CacheError::PinBound));480 assert!(fs::read_dir(dir.join(".tmp")).unwrap().next().is_none());481 }482 483 fn on(base: &str, name: &str) -> PathBuf {484 let dir = Path::new(base).join(format!(485 "inf3r-cache-test-{name}-{}-{}",486 std::process::id(),487 now()488 ));489 let _ = fs::remove_dir_all(&dir);490 fs::create_dir_all(&dir).unwrap();491 fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();492 dir493 }494 495 fn two_tiers(hot: &Path, cold: &Path, hot_bound: u64, cold_bound: u64) -> CacheConfig {496 CacheConfig {497 enabled: true,498 persist: Persist::Reboot,499 pin_bound: 0,500 flush_budget: Duration::from_secs(1),501 default_ttl: Duration::from_secs(3600),502 classes: BTreeMap::new(),503 tiers: vec![504 TierConfig {505 name: "hot".into(),506 dir: hot.to_path_buf(),507 bound: Some(hot_bound),508 headroom: 0,509 ttl: None,510 },511 TierConfig {512 name: "cold".into(),513 dir: cold.to_path_buf(),514 bound: Some(cold_bound),515 headroom: 0,516 ttl: None,517 },518 ],519 blob_dir: PathBuf::new(),520 }521 }522 523 fn save(cache: &Cache, session: u64, k: u8, bytes: usize, prefill_ms: u64) -> [u8; 32] {524 let payload = vec![k; bytes];525 let lease = cache526 .reserve(527 session,528 key(k),529 None,530 None,531 EntryKind::Tip,532 bytes as u64,533 prefill_ms,534 1,535 false,536 )537 .unwrap();538 let id = lease.lease_id();539 lease540 .file()541 .try_clone()542 .unwrap()543 .write_all(&payload)544 .unwrap();545 cache546 .commit(547 session,548 id,549 bytes as u64,550 inf3r_cache::crc32c(&payload),551 1,552 1,553 )554 .unwrap();555 drop(lease);556 key(k)557 }558 559 fn open_bundle(cache: &Cache, session: u64, bundle: &str, fingerprint: [u8; 32]) {560 cache561 .open_session(562 session,563 bundle,564 fingerprint,565 spec(1024 * 1024),566 Duration::from_secs(3600),567 )568 .unwrap();569 }570 571 #[test]572 fn an_economic_demotion_and_second_hit_promotion_cross_tiers() {573 let _one = one();574 let hot = on("/dev/shm", "hot-demote");575 let cold = on("/var/tmp", "cold-demote");576 let cache = Cache::open(two_tiers(&hot, &cold, 1 << 20, 4 << 20)).unwrap();577 open(&cache, 1, fp(1));578 save(&cache, 1, 1, 64 * 1024, 1000);579 580 // Establish the cold tier's measured read rate first. Economic demotion581 // must use the target tier's own number, not the source tier's.582 cache.relieve_ram(64 * 1024);583 let hit = cache.lookup(1, &[key(1)], None).unwrap().unwrap();584 hit.release_metered(true, 20);585 586 save(&cache, 1, 2, 64 * 1024, 1000);587 let moved = cache.maintain();588 assert_eq!(moved.demoted, 1, "{moved:?}");589 let entry = cache590 .entries()591 .into_iter()592 .find(|m| m.key == key(2))593 .unwrap();594 assert_eq!(entry.tier, 1, "the entry must be on the cold tier");595 596 // A second hit schedules promotion; a background pass moves it back while597 // keeping the entry hot afterwards.598 for _ in 0..2 {599 let hit = cache.lookup(1, &[key(2)], None).unwrap().unwrap();600 hit.release(true);601 }602 let moved = cache.maintain();603 assert!(moved.promoted >= 1, "{moved:?}");604 let entry = cache605 .entries()606 .into_iter()607 .find(|m| m.key == key(2))608 .unwrap();609 assert_eq!(entry.tier, 0, "the second hit must promote to the hot tier");610 }611 612 #[test]613 fn disk_pressure_evicts_only_the_named_filesystem() {614 let _one = one();615 let hot = on("/dev/shm", "pressure-hot");616 let cold = on("/var/tmp", "pressure-cold");617 let cache = Cache::open(two_tiers(&hot, &cold, 1 << 20, 4 << 20)).unwrap();618 open(&cache, 1, fp(1));619 save(&cache, 1, 1, 32 * 1024, 1000);620 // Force the hot entry to the cold tier, then add one entry per tier.621 cache.relieve_ram(32 * 1024);622 save(&cache, 1, 2, 32 * 1024, 1000);623 let filesystems = cache.filesystems();624 let hot_dev = filesystems[0].0;625 let cold_dev = filesystems[1].0;626 assert_ne!(hot_dev, cold_dev);627 let evicted = cache.pressure(hot_dev, u64::MAX);628 assert_eq!(evicted, 1);629 assert!(630 cache631 .entries()632 .iter()633 .all(|meta| usize::from(meta.tier) != 0),634 "the hot tier must be empty"635 );636 assert!(637 cache638 .entries()639 .iter()640 .any(|meta| usize::from(meta.tier) == 1),641 "the cold tier must survive pressure on another device"642 );643 }644 645 #[test]646 fn two_bundles_share_a_full_tier_without_starving_each_other() {647 let _one = one();648 let dir = temp("fairness");649 let cache = Cache::open(config(&dir, 120 * 1024)).unwrap();650 open_bundle(&cache, 1, "a/model", fp(1));651 open_bundle(&cache, 2, "b/model", fp(2));652 save(&cache, 1, 1, 50 * 1024, 1000);653 save(&cache, 1, 2, 50 * 1024, 1000);654 // The second model needs room. The largest model yields, so b gets a655 // checkpoint and a only loses one of its two.656 save(&cache, 2, 3, 50 * 1024, 1000);657 let mut a = 0;658 let mut b = 0;659 for meta in cache.entries() {660 if meta.bundle == "a/model" {661 a += 1;662 } else if meta.bundle == "b/model" {663 b += 1;664 }665 }666 assert_eq!(a, 1, "a must keep a live checkpoint");667 assert_eq!(b, 1, "b must not be locked out");668 // Filling b further must give a its share back rather than evicting every669 // entry of a.670 save(&cache, 2, 4, 50 * 1024, 1000);671 assert!(cache.entries().iter().any(|meta| meta.bundle == "a/model"));672 assert!(cache.entries().iter().any(|meta| meta.bundle == "b/model"));673 }674 675 #[test]676 fn relieving_ram_demotes_before_it_evicts() {677 let _one = one();678 let hot = on("/dev/shm", "relieve-hot");679 let cold = on("/var/tmp", "relieve-cold");680 let cache = Cache::open(two_tiers(&hot, &cold, 1 << 20, 4 << 20)).unwrap();681 open(&cache, 1, fp(1));682 save(&cache, 1, 1, 64 * 1024, 1000);683 let moved = cache.relieve_ram(64 * 1024);684 assert_eq!(moved, 1);685 assert!(686 cache687 .entries()688 .iter()689 .all(|meta| usize::from(meta.tier) != 0)690 );691 assert_eq!(cache.len(), 1, "the bytes must survive a demotion");692 assert_eq!(cache.stats().tiers[1].demotions_in, 1);693 }694 695 #[test]696 fn a_demotion_survives_a_restart() {697 let _one = one();698 let hot = on("/dev/shm", "demote-restart-hot");699 let cold = on("/var/tmp", "demote-restart-cold");700 {701 let cache = Cache::open(two_tiers(&hot, &cold, 1 << 20, 4 << 20)).unwrap();702 open(&cache, 1, fp(1));703 save(&cache, 1, 1, 64 * 1024, 1000);704 cache.relieve_ram(64 * 1024);705 }706 let cache = Cache::open(two_tiers(&hot, &cold, 1 << 20, 4 << 20)).unwrap();707 open(&cache, 1, fp(1));708 let entry = cache709 .entries()710 .into_iter()711 .find(|m| m.key == key(1))712 .unwrap();713 assert_eq!(entry.tier, 1, "the cold tier is where the entry landed");714 assert!(cache.lookup(1, &[key(1)], None).unwrap().is_some());715 }716 717 #[test]718 fn a_fingerprint_change_retires_the_old_bundle_entries() {719 let _one = one();720 let dir = temp("invalidate");721 let cache = Cache::open(config(&dir, 1024 * 1024)).unwrap();722 open(&cache, 1, fp(1));723 save(&cache, 1, 1, 16 * 1024, 1000);724 assert_eq!(cache.len(), 1);725 assert_eq!(cache.invalidate_bundle("test/1x0", fp(2)), 1);726 assert!(cache.is_empty());727 assert!(fs::read_dir(dir.join("entries")).unwrap().all(|entry| {728 entry729 .map(|entry| {730 fs::read_dir(entry.path())731 .map(|mut d| d.next().is_none())732 .unwrap_or(true)733 })734 .unwrap_or(true)735 }));736 }737 738 fn restore_only_spec(max: u64) -> CacheSpec {739 CacheSpec {740 supports_save: false,741 supports_restore: true,742 ..spec(max)743 }744 }745 746 #[test]747 fn a_restore_only_declaration_opens_and_cannot_reserve() {748 let _one = one();749 let dir = temp("restore-only");750 let cache = Cache::open(config(&dir, 1 << 20)).unwrap();751 open(&cache, 1, fp(1));752 save(&cache, 1, 1, 32, 100);753 cache754 .open_session(755 2,756 "restore/only",757 fp(1),758 restore_only_spec(1 << 20),759 Duration::from_secs(3600),760 )761 .unwrap();762 let hit = cache.lookup(2, &[key(1)], None).unwrap().expect("hit");763 hit.release_metered(true, 1);764 let err = cache765 .reserve(2, key(2), None, None, EntryKind::Tip, 32, 100, 1, false)766 .unwrap_err();767 assert!(matches!(err, inf3r_cache::CacheError::Invalid(_)));768 }769 770 #[test]771 fn a_reservation_cannot_commit_more_than_it_reserved() {772 let _one = one();773 let dir = temp("overrun");774 let cache = Cache::open(config(&dir, 16)).unwrap();775 open(&cache, 1, fp(1));776 let lease = cache777 .reserve(1, key(1), None, None, EntryKind::Tip, 4, 100, 1, false)778 .unwrap();779 let id = lease.lease_id();780 lease781 .file()782 .try_clone()783 .unwrap()784 .write_all(b"eight-byte payload")785 .unwrap();786 let err = cache787 .commit(1, id, 18, inf3r_cache::crc32c(b"eight-byte payload"), 1, 1)788 .unwrap_err();789 assert!(matches!(err, inf3r_cache::CacheError::Full), "{err:?}");790 drop(lease);791 assert_eq!(cache.len(), 0);792 assert_eq!(cache.temp_files(), 0);793 }794 795 #[test]796 fn a_retiring_entry_cannot_be_recommitted_under_the_same_key() {797 let _one = one();798 let dir = temp("retire-race");799 let cache = Cache::open(config(&dir, 1 << 20)).unwrap();800 open(&cache, 1, fp(1));801 save(&cache, 1, 1, 32, 100);802 let hit = cache.lookup(1, &[key(1)], None).unwrap().expect("hit");803 let id = entry_id(fp(1), &key(1));804 assert!(cache.evict_id(&id));805 let err = cache806 .reserve(1, key(1), None, None, EntryKind::Tip, 32, 100, 1, false)807 .unwrap_err();808 assert!(matches!(err, inf3r_cache::CacheError::Busy(_)));809 hit.release_metered(true, 1);810 save(&cache, 1, 1, 32, 100);811 assert_eq!(cache.len(), 1);812 }813 814 #[test]815 fn a_zero_pin_bound_means_no_pins_not_unlimited_pins() {816 let _one = one();817 let dir = temp("pin-zero");818 let mut cfg = config(&dir, 1 << 20);819 cfg.pin_bound = 0;820 let cache = Cache::open(cfg).unwrap();821 open(&cache, 1, fp(1));822 let err = cache823 .reserve(1, key(1), None, None, EntryKind::Tip, 32, 100, 1, true)824 .unwrap_err();825 assert!(matches!(err, inf3r_cache::CacheError::PinBound));826 }827 828 #[test]829 fn a_pinned_entry_does_not_expire() {830 let _one = one();831 let dir = temp("pin-ttl");832 let mut cfg = config(&dir, 1 << 20);833 cfg.pin_bound = 1 << 19;834 cfg.default_ttl = Duration::from_millis(1);835 let cache = Cache::open(cfg).unwrap();836 cache837 .open_session(838 1,839 "test/1x0",840 fp(1),841 spec(1 << 20),842 Duration::from_millis(1),843 )844 .unwrap();845 let lease = cache846 .reserve(1, key(1), None, None, EntryKind::Tip, 32, 100, 1, true)847 .unwrap();848 let lease_id = lease.lease_id();849 lease850 .file()851 .try_clone()852 .unwrap()853 .write_all(&[1u8; 32])854 .unwrap();855 cache856 .commit(1, lease_id, 32, inf3r_cache::crc32c(&[1u8; 32]), 1, 1)857 .unwrap();858 std::thread::sleep(Duration::from_millis(5));859 assert_eq!(cache.maintain().expired, 0);860 let hit = cache861 .lookup(1, &[key(1)], None)862 .unwrap()863 .expect("pinned hit");864 hit.release_metered(true, 1);865 cache.set_pinned(&entry_id(fp(1), &key(1)), false).unwrap();866 assert!(cache.lookup(1, &[key(1)], None).unwrap().is_none());867 }868 869 #[test]870 fn the_over_share_bundle_yields_before_a_below_share_bundle() {871 let _one = one();872 let dir = temp("fair-three");873 let cache = Cache::open(config(&dir, 120 * 1024)).unwrap();874 open_bundle(&cache, 1, "a/model", fp(1));875 open_bundle(&cache, 2, "b/model", fp(2));876 open_bundle(&cache, 3, "c/model", fp(3));877 save(&cache, 1, 1, 50 * 1024, 1000);878 save(&cache, 1, 2, 50 * 1024, 1000);879 // c has no entries. The first victim must be a's over-share entry, not880 // some other below-share bundle's only checkpoint.881 save(&cache, 2, 3, 20 * 1024, 1000);882 assert!(cache.entries().iter().any(|meta| meta.bundle == "b/model"));883 let a = cache884 .entries()885 .iter()886 .filter(|meta| meta.bundle == "a/model")887 .count();888 assert!(a <= 2);889 }890 891 #[test]892 fn a_different_directory_on_the_same_device_is_still_one_authority() {893 let _one = one();894 let first = temp("authority-a");895 let second = on(first.parent().unwrap().to_str().unwrap(), "authority-b");896 let cache = Cache::open(config(&first, 1 << 20)).unwrap();897 let err = Cache::open(config(&second, 1 << 20)).unwrap_err();898 assert!(matches!(err, inf3r_cache::CacheError::Busy(_)), "{err:?}");899 drop(cache);900 }901 902 #[test]903 fn an_unbounded_tier_needs_headroom() {904 let _one = one();905 let dir = temp("unbounded");906 let mut cfg = config(&dir, 1 << 20);907 cfg.tiers[0].bound = None;908 cfg.tiers[0].headroom = 0;909 assert!(matches!(910 Cache::open(cfg).unwrap_err(),911 inf3r_cache::CacheError::Layout(_)912 ));913 }914 915 #[test]916 fn a_disk_tier_before_a_ram_tier_is_refused() {917 let _one = one();918 let disk = on("/var/tmp", "order-disk");919 let ram = on("/dev/shm", "order-ram");920 let mut cfg = two_tiers(&disk, &ram, 1 << 20, 1 << 20);921 cfg.pin_bound = 0;922 assert!(matches!(923 Cache::open(cfg).unwrap_err(),924 inf3r_cache::CacheError::Layout(_)925 ));926 }927 928 #[test]929 fn a_symlinked_wal_is_not_followed() {930 let _one = one();931 let dir = temp("symlink-wal");932 {933 let cache = Cache::open(config(&dir, 1 << 20)).unwrap();934 open(&cache, 1, fp(1));935 save(&cache, 1, 1, 32, 100);936 }937 let outside = dir.join("outside.log");938 fs::write(&outside, b"not a wal").unwrap();939 fs::remove_file(dir.join("index.log")).unwrap();940 std::os::unix::fs::symlink(&outside, dir.join("index.log")).unwrap();941 let err = Cache::open(config(&dir, 1 << 20)).unwrap_err();942 assert!(matches!(err, inf3r_cache::CacheError::Io { .. }), "{err:?}");943 }944 945 #[test]946 fn two_tiers_on_one_filesystem_are_a_layout_error() {947 let _one = one();948 let base = temp("same-dev");949 let first = base.join("hot");950 let second = base.join("cold");951 let mut cfg = config(&first, 1 << 20);952 cfg.tiers.push(TierConfig {953 name: "cold".into(),954 dir: second,955 bound: Some(1 << 20),956 headroom: 0,957 ttl: None,958 });959 assert!(matches!(960 Cache::open(cfg).unwrap_err(),961 inf3r_cache::CacheError::Layout(_)962 ));963 }964 965 #[test]966 fn an_abandoned_read_is_not_a_hit_and_holds_nothing() {967 let _one = one();968 let dir = temp("abandon");969 let cache = Cache::open(config(&dir, 1 << 20)).unwrap();970 open(&cache, 1, fp(1));971 save(&cache, 1, 1, 32, 700);972 let hit = cache.lookup(1, &[key(1)], None).unwrap().expect("hit");973 let lease = hit.lease_id();974 cache.abandon_read(1, lease);975 drop(hit);976 let stats = cache.stats();977 assert_eq!(stats.hits, 0);978 assert_eq!(stats.active_reads, 0);979 assert_eq!(stats.saved_prefill_ms_total, 0);980 }981 982 #[test]983 fn a_trivial_prompt_is_refused_once_restore_economics_are_measured() {984 let _one = one();985 let dir = temp("admission");986 let cache = Cache::open(config(&dir, 1 << 20)).unwrap();987 open(&cache, 1, fp(1));988 save(&cache, 1, 1, 64 * 1024, 1000);989 let hit = cache.lookup(1, &[key(1)], None).unwrap().unwrap();990 hit.release_metered(true, 100);991 let err = cache992 .reserve(993 1,994 key(2),995 None,996 None,997 EntryKind::Tip,998 64 * 1024,999 50,1000 1,1001 false,1002 )1003 .unwrap_err();1004 assert!(matches!(err, inf3r_cache::CacheError::Admission));1005 }1006 1007 #[test]1008 fn a_failed_restore_is_not_a_hit_and_is_counted_as_corrupt() {1009 let _one = one();1010 let dir = temp("corrupt-stat");1011 let cache = Cache::open(config(&dir, 1 << 20)).unwrap();1012 open(&cache, 1, fp(1));1013 save(&cache, 1, 1, 32, 900);1014 let hit = cache.lookup(1, &[key(1)], None).unwrap().unwrap();1015 hit.release_metered(false, 5);1016 let stats = cache.stats();1017 assert_eq!(stats.hits, 0);1018 assert_eq!(stats.saved_prefill_ms_total, 0);1019 assert_eq!(stats.corrupt_entries, 1);1020 assert_eq!(stats.evictions.corrupt, 1);1021 }1022 1023 #[test]1024 fn a_tier_overlapping_the_blob_directory_is_refused_after_canonicalisation() {1025 let _one = one();1026 let base = temp("blob-overlap");1027 let blobs = base.join("blobs");1028 fs::create_dir_all(&blobs).unwrap();1029 let tier = base.join("cache");1030 fs::create_dir_all(&tier).unwrap();1031 fs::set_permissions(&tier, fs::Permissions::from_mode(0o700)).unwrap();1032 let mut cfg = config(&tier, 1 << 20);1033 cfg.blob_dir = blobs.join("..").join("cache");1034 assert!(matches!(1035 Cache::open(cfg).unwrap_err(),1036 inf3r_cache::CacheError::Layout(_)1037 ));1038 }