1 //! The engine-neutral cache driver without HTTP, ports, or a staging tree.2 //!3 //! The fake slot stands in for a direct FFI bundle; the fake transport stands4 //! in for the core. Every key, anchor, restore, and commit still crosses the5 //! real SDK driver and the real descriptor checks.6 7 use std::collections::BTreeMap;8 use std::fs::{self, File, OpenOptions};9 use std::io::{Read, Seek, SeekFrom, Write};10 use std::os::unix::fs::PermissionsExt;11 use std::path::{Path, PathBuf};12 use std::sync::atomic::{AtomicU64, Ordering};13 use std::sync::{Arc, Mutex};14 use std::time::Duration;15 16 use inf3r_plugin_sdk::cache::{17 CacheCodec, CacheDriver, CacheFile, CacheSlot, CacheTransport, CacheWrite, Chain, FlushReport,18 PrefixOutcome, PrefixReply, Reserve,19 };20 use inf3r_plugin_sdk::capability::{Part, PartBody, Request};21 use inf3r_proto::Value;22 use inf3r_proto::body::{CacheEntryKind, CacheStateKind, PartKind};23 24 static NEXT: AtomicU64 = AtomicU64::new(0);25 26 struct TempDir(PathBuf);27 28 impl TempDir {29 fn new() -> TempDir {30 let path = std::env::temp_dir().join(format!(31 "inf3r-cache-driver-{}-{}",32 std::process::id(),33 NEXT.fetch_add(1, Ordering::SeqCst)34 ));35 fs::create_dir_all(&path).unwrap();36 fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();37 TempDir(path)38 }39 }40 41 impl Drop for TempDir {42 fn drop(&mut self) {43 let _ = fs::remove_dir_all(&self.0);44 }45 }46 47 fn text<'a>(role: &'a str, body: &'a str) -> Part<'a> {48 Part {49 kind: PartKind::Text,50 mime: "text/plain",51 role: Some(role),52 len: body.len() as u64,53 body: PartBody::Inline(body.as_bytes()),54 }55 }56 57 fn tools<'a>(body: &'a str) -> Part<'a> {58 Part {59 kind: PartKind::Json,60 mime: "application/json",61 role: Some("tools"),62 len: body.len() as u64,63 body: PartBody::Inline(body.as_bytes()),64 }65 }66 67 fn request<'a>(parts: &'a [Part<'a>], params: &'a Value) -> Request<'a> {68 Request {69 request_id: "test",70 model: "mock",71 capability: "chat",72 parts,73 params,74 }75 }76 77 fn cache_key_param(key: &str) -> Value {78 Value::map([(Value::Text("cache_key".into()), Value::Text(key.into()))])79 }80 81 #[derive(Default)]82 struct SlotState {83 bytes: Vec<u8>,84 erases: u32,85 }86 87 #[derive(Clone)]88 struct Slot {89 state: Arc<Mutex<SlotState>>,90 prefix: bool,91 }92 93 impl Slot {94 fn new(prefix: bool) -> Slot {95 Slot {96 state: Arc::new(Mutex::new(SlotState::default())),97 prefix,98 }99 }100 101 fn bytes(&self) -> Vec<u8> {102 self.state.lock().unwrap().bytes.clone()103 }104 105 fn erases(&self) -> u32 {106 self.state.lock().unwrap().erases107 }108 }109 110 impl CacheSlot for Slot {111 fn prefix_checkpoint(&self, _timeout: Duration) -> std::io::Result<bool> {112 Ok(self.prefix)113 }114 115 fn restore(&self, _slot: u32, file: &CacheFile, _timeout: Duration) -> std::io::Result<()> {116 let mut source = File::from(file.file.try_clone()?);117 let mut bytes = Vec::new();118 source.read_to_end(&mut bytes)?;119 self.state.lock().unwrap().bytes = bytes;120 Ok(())121 }122 123 fn save(&self, _slot: u32, file: &CacheWrite, _timeout: Duration) -> std::io::Result<()> {124 let bytes = self.state.lock().unwrap().bytes.clone();125 let mut target = File::from(file.file.try_clone()?);126 target.seek(SeekFrom::Start(0))?;127 target.set_len(0)?;128 target.write_all(&bytes)?;129 target.sync_all()?;130 Ok(())131 }132 133 fn erase(&self, _slot: u32, _timeout: Duration) -> std::io::Result<()> {134 let mut state = self.state.lock().unwrap();135 state.bytes.clear();136 state.erases += 1;137 Ok(())138 }139 140 fn prepare_prefix(141 &self,142 _req: &Request<'_>,143 _chain: &Chain<'_>,144 _timeout: Duration,145 ) -> std::io::Result<PrefixOutcome> {146 self.state.lock().unwrap().bytes = b"anchor-prefix".to_vec();147 Ok(PrefixOutcome::Prepared(PrefixReply {148 tokens: 2,149 prefill_ms: 10,150 }))151 }152 }153 154 #[derive(Clone)]155 struct Entry {156 bytes: Vec<u8>,157 path: PathBuf,158 }159 160 struct Pending {161 key: [u8; 32],162 path: PathBuf,163 }164 165 struct Transport {166 dir: PathBuf,167 entries: Mutex<BTreeMap<[u8; 32], Entry>>,168 pending: Mutex<BTreeMap<u64, Pending>>,169 next: AtomicU64,170 reserves: Mutex<Vec<Reserve>>,171 commits: Mutex<Vec<(bool, u64)>>,172 releases: Mutex<Vec<(u64, bool)>>,173 }174 175 impl Transport {176 fn new(dir: &Path) -> Transport {177 Transport {178 dir: dir.to_path_buf(),179 entries: Mutex::new(BTreeMap::new()),180 pending: Mutex::new(BTreeMap::new()),181 next: AtomicU64::new(1),182 reserves: Mutex::new(Vec::new()),183 commits: Mutex::new(Vec::new()),184 releases: Mutex::new(Vec::new()),185 }186 }187 188 fn seed(&self, key: [u8; 32], bytes: &[u8]) {189 let path = self.dir.join(format!(190 "entry-{}",191 self.next.fetch_add(1, Ordering::SeqCst)192 ));193 fs::write(&path, bytes).unwrap();194 self.entries.lock().unwrap().insert(195 key,196 Entry {197 bytes: bytes.to_vec(),198 path,199 },200 );201 }202 203 fn corrupt(&self, key: &[u8; 32]) {204 if let Some(entry) = self.entries.lock().unwrap().get_mut(key) {205 entry.bytes[0] ^= 1;206 }207 }208 209 fn reserves(&self) -> Vec<Reserve> {210 self.reserves.lock().unwrap().clone()211 }212 213 fn commits(&self) -> Vec<(bool, u64)> {214 self.commits.lock().unwrap().clone()215 }216 217 fn releases(&self) -> Vec<(u64, bool)> {218 self.releases.lock().unwrap().clone()219 }220 }221 222 impl CacheTransport for Transport {223 fn lookup(224 &self,225 keys: &[[u8; 32]],226 _lineage: Option<[u8; 32]>,227 _timeout: Duration,228 ) -> std::io::Result<Option<CacheFile>> {229 let entries = self.entries.lock().unwrap();230 for key in keys {231 if let Some(entry) = entries.get(key) {232 let file = File::open(&entry.path)?;233 return Ok(Some(CacheFile {234 key: *key,235 lease_id: 1,236 bytes: entry.bytes.len() as u64,237 crc32c: inf3r_cache::crc32c(&entry.bytes),238 token_count: 2,239 tier: "test".into(),240 file: file.into(),241 }));242 }243 }244 Ok(None)245 }246 247 fn reserve(&self, request: Reserve, _timeout: Duration) -> std::io::Result<Option<CacheWrite>> {248 let lease = self.next.fetch_add(1, Ordering::SeqCst);249 let path = self.dir.join(format!("lease-{lease}.bin"));250 let file = OpenOptions::new()251 .read(true)252 .write(true)253 .create(true)254 .truncate(true)255 .open(&path)?;256 self.pending.lock().unwrap().insert(257 lease,258 Pending {259 key: request.key,260 path,261 },262 );263 self.reserves.lock().unwrap().push(request);264 Ok(Some(CacheWrite {265 lease_id: lease,266 max_bytes: 4096,267 tier: "test".into(),268 file: file.into(),269 }))270 }271 272 fn release(&self, lease_id: u64, ok: bool, _restore_ms: u32) -> std::io::Result<()> {273 self.releases.lock().unwrap().push((lease_id, ok));274 Ok(())275 }276 277 fn commit(278 &self,279 lease_id: u64,280 ok: bool,281 bytes: u64,282 _crc32c: u32,283 _token_count: u64,284 _save_ms: u32,285 ) -> std::io::Result<()> {286 self.commits.lock().unwrap().push((ok, bytes));287 let Some(pending) = self.pending.lock().unwrap().remove(&lease_id) else {288 return Ok(());289 };290 if ok {291 let content = fs::read(&pending.path)?;292 self.entries.lock().unwrap().insert(293 pending.key,294 Entry {295 bytes: content,296 path: pending.path,297 },298 );299 } else {300 let _ = fs::remove_file(&pending.path);301 }302 Ok(())303 }304 }305 306 fn driver(slot: Slot, transport: Arc<Transport>) -> Arc<CacheDriver<Slot>> {307 let driver = Arc::new(CacheDriver::new(308 inf3r_proto::body::CacheSpec {309 codec_version: 1,310 slots: 1,311 state_kind: CacheStateKind::CheckpointExact,312 max_entry_bytes: 4096,313 local_ram_bytes: 0,314 supports_save: true,315 supports_restore: true,316 supports_erase: true,317 },318 [9; 32],319 1,320 slot,321 ));322 driver.attach(transport);323 driver324 }325 326 #[test]327 fn a_shared_anchor_is_saved_then_restored_by_another_lineage() {328 let temp = TempDir::new();329 let transport = Arc::new(Transport::new(&temp.0));330 let slot = Slot::new(true);331 let cache = driver(slot.clone(), Arc::clone(&transport));332 assert_eq!(333 cache.spec().state_kind,334 CacheStateKind::CheckpointExact,335 "a hybrid or SSM model never rolls back"336 );337 338 let system = text("system", "be brief");339 let tool = tools(r#"{"tools":[{"type":"function"}]}"#);340 let user_a = text("user", "alpha");341 let params_a = cache_key_param("conversation-a");342 let parts_a = [system, tool, user_a];343 let first = request(&parts_a, ¶ms_a);344 cache345 .restore(&first, Duration::from_secs(2), Duration::from_secs(2))346 .unwrap();347 assert_eq!(cache.cached_tokens(), 0);348 assert_eq!(slot.bytes(), b"anchor-prefix");349 let anchor = Chain::new(&first).unwrap().anchor.unwrap();350 {351 let reserves = transport.reserves();352 assert_eq!(reserves.len(), 1);353 assert_eq!(reserves[0].key, anchor);354 assert_eq!(reserves[0].kind, CacheEntryKind::Anchor);355 assert_eq!(reserves[0].supersedes, None);356 assert_eq!(transport.commits(), vec![(true, 13)]);357 }358 359 let user_b = text("user", "beta");360 let params_b = cache_key_param("conversation-b");361 let parts_b = [system, tool, user_b];362 let second = request(&parts_b, ¶ms_b);363 cache364 .restore(&second, Duration::from_secs(2), Duration::from_secs(2))365 .unwrap();366 assert_eq!(cache.cached_tokens(), 2);367 assert_eq!(slot.bytes(), b"anchor-prefix");368 assert_eq!(transport.releases(), vec![(1, true)]);369 370 cache371 .after_turn(&second, "answer-b", 10, 2, Duration::from_secs(2))372 .unwrap();373 assert_eq!(374 cache.flush(Duration::from_secs(2)),375 FlushReport {376 saved: 0,377 skipped: 0,378 dirty_remaining: 0,379 }380 );381 let reserves = transport.reserves();382 assert_eq!(reserves.len(), 2);383 assert_eq!(reserves[1].kind, CacheEntryKind::Tip);384 assert_eq!(reserves[1].supersedes, None);385 assert_eq!(386 reserves[1].lineage,387 Some(Chain::new(&second).unwrap().lineage)388 );389 assert_eq!(transport.commits().len(), 2);390 assert!(transport.commits()[1].0);391 392 let assistant = text("assistant", "answer-b");393 let parts_next = [system, tool, user_b, assistant];394 let next = request(&parts_next, ¶ms_b);395 cache396 .restore(&next, Duration::from_secs(2), Duration::from_secs(2))397 .unwrap();398 assert_eq!(cache.cached_tokens(), 2);399 assert_eq!(transport.releases().last(), Some(&(1, true)));400 401 cache.taint();402 cache403 .restore(&next, Duration::from_secs(2), Duration::from_secs(2))404 .unwrap();405 assert_eq!(slot.erases(), 1);406 assert_eq!(cache.cached_tokens(), 2);407 }408 409 #[test]410 fn a_corrupt_entry_is_released_and_the_slot_is_erased() {411 let temp = TempDir::new();412 let transport = Arc::new(Transport::new(&temp.0));413 let slot = Slot::new(false);414 let cache = driver(slot.clone(), Arc::clone(&transport));415 416 let system = text("system", "be brief");417 let user = text("user", "alpha");418 let params = Value::Null;419 let parts = [system, user];420 let req = request(&parts, ¶ms);421 let chain = Chain::new(&req).unwrap();422 let key = *chain.keys.last().unwrap();423 transport.seed(key, b"bad");424 transport.corrupt(&key);425 426 cache427 .restore(&req, Duration::from_secs(2), Duration::from_secs(2))428 .unwrap();429 assert_eq!(cache.cached_tokens(), 0);430 assert_eq!(slot.erases(), 1);431 assert_eq!(transport.releases(), vec![(1, false)]);432 assert!(transport.reserves().is_empty());433 }434 435 #[test]436 fn a_cache_without_a_transport_still_erases_the_slot() {437 let temp = TempDir::new();438 let slot = Slot::new(false);439 let cache = Arc::new(CacheDriver::new(440 inf3r_proto::body::CacheSpec {441 codec_version: 1,442 slots: 1,443 state_kind: CacheStateKind::CheckpointExact,444 max_entry_bytes: 4096,445 local_ram_bytes: 0,446 supports_save: true,447 supports_restore: true,448 supports_erase: true,449 },450 [9; 32],451 1,452 slot.clone(),453 ));454 let system = text("system", "be brief");455 let user = text("user", "alpha");456 let params = Value::Null;457 let parts = [system, user];458 let req = request(&parts, ¶ms);459 cache460 .restore(&req, Duration::from_secs(2), Duration::from_secs(2))461 .unwrap();462 assert_eq!(slot.erases(), 1);463 let _ = temp;464 }