crates/edge/sdk/tests/cache.rs 8.6 KiB 282 lines Raw
1 //! Wire 2 end to end: a plugin asks the core for a cache descriptor, writes it,2 //! commits it, and reads it back on the next job.3 4 use std::fs;5 use std::io::{Read, Write};6 use std::os::unix::fs::PermissionsExt;7 use std::os::unix::net::UnixStream;8 use std::sync::{Arc, Mutex, OnceLock};9 use std::thread;10 use std::time::Duration;11 12 use inf3r_cache::{Cache, CacheConfig, Persist, TierConfig};13 use inf3r_core::CacheRuntime;14 use inf3r_plugin_sdk::cache::{15     CacheCodec, CacheFile, CacheTransport, CacheWrite, FlushReport, Reserve,16 };17 use inf3r_plugin_sdk::capability::{Report, Request};18 use inf3r_plugin_sdk::emitter::Emitter;19 use inf3r_plugin_sdk::serve::{Plugin, serve};20 use inf3r_proto::body::{21     CacheEntryKind, CacheSpec, CacheStateKind, Capability, Catalogue, Grant, Model, Part, PartKind,22     Ready, Target,23 };24 use inf3r_proto::client::Peer;25 use std::collections::BTreeMap;26 27 const KEY: [u8; 32] = [7; 32];28 const PAYLOAD: &[u8] = b"slot bytes";29 30 struct Codec {31     transport: OnceLock<Arc<dyn CacheTransport>>,32 }33 34 impl CacheCodec for Codec {35     fn spec(&self) -> CacheSpec {36         CacheSpec {37             codec_version: 1,38             slots: 1,39             state_kind: CacheStateKind::CheckpointExact,40             max_entry_bytes: 4096,41             local_ram_bytes: 0,42             supports_save: true,43             supports_restore: true,44             supports_erase: true,45         }46     }47 48     fn fingerprint(&self) -> [u8; 32] {49         [9; 32]50     }51 52     fn attach(&self, transport: Arc<dyn CacheTransport>) {53         let _ = self.transport.set(transport);54     }55 56     fn flush(&self, _budget: Duration) -> FlushReport {57         FlushReport::default()58     }59 60     fn erase(&self, _slot: u32) -> std::io::Result<()> {61         Ok(())62     }63 }64 65 struct PluginImpl {66     codec: Arc<Codec>,67     hit: Arc<Mutex<bool>>,68     miss: Arc<Mutex<bool>>,69 }70 71 impl Plugin for PluginImpl {72     fn max_inflight(&self) -> u16 {73         174     }75 76     fn catalogue(&self) -> Catalogue {77         let mut caps = BTreeMap::new();78         caps.insert(79             "chat".into(),80             Capability {81                 vocab: "chat.v1".into(),82                 parts: vec![PartKind::Text],83                 channels: vec!["text".into()],84                 limits: BTreeMap::new(),85                 cancel: inf3r_proto::body::Cancel::Token,86                 stops: inf3r_proto::body::Stops::Plugin,87                 queue: inf3r_proto::body::Queue::None,88             },89         );90         Catalogue {91             target: Target {92                 id: "cpu".into(),93                 backend: "mock".into(),94                 arch: vec!["x86_64".into()],95                 devices: 0,96                 vram_mb: Vec::new(),97             },98             models: vec![Model {99                 serve: "cache-test".into(),100                 alias_of: None,101                 weights_bytes: 0,102                 load_ms: 0,103                 capabilities: caps,104             }],105             runtime: None,106             cache: Some(self.codec.spec()),107         }108     }109 110     fn cache(&self) -> Option<Arc<dyn CacheCodec>> {111         Some(Arc::clone(&self.codec) as Arc<dyn CacheCodec>)112     }113 114     fn load(&self, _grant: &Grant) -> Result<Ready, inf3r_plugin_sdk::Failure> {115         Ok(Ready {116             load_ms: 1,117             cache_fingerprint: None,118         })119     }120 121     fn run(122         &self,123         _capability: &str,124         _req: Request<'_>,125         out: &mut dyn Emitter,126     ) -> Result<Report, inf3r_plugin_sdk::Failure> {127         let transport = self.codec.transport.get().unwrap();128         let hit = transport129             .lookup(&[KEY], None, Duration::from_secs(2))130             .map_err(|why| {131                 inf3r_plugin_sdk::Failure::new(132                     inf3r_proto::body::ErrorCode::Internal,133                     why.to_string(),134                 )135             })?;136         if let Some(file) = hit {137             assert_eq!(read(&file), PAYLOAD);138             transport.release(file.lease_id, true, 1).unwrap();139             *self.hit.lock().unwrap() = true;140         } else {141             *self.miss.lock().unwrap() = true;142             let write = transport143                 .reserve(144                     Reserve {145                         key: KEY,146                         lineage: None,147                         supersedes: None,148                         kind: CacheEntryKind::Tip,149                         est_bytes: PAYLOAD.len() as u64,150                         prefill_ms: 50,151                         token_count: 2,152                         pin: false,153                     },154                     Duration::from_secs(2),155                 )156                 .map_err(|why| {157                     inf3r_plugin_sdk::Failure::new(158                         inf3r_proto::body::ErrorCode::Internal,159                         why.to_string(),160                     )161                 })?162                 .expect("a write grant");163             write_bytes(&write);164             transport165                 .commit(166                     write.lease_id,167                     true,168                     PAYLOAD.len() as u64,169                     inf3r_cache::crc32c(PAYLOAD),170                     2,171                     1,172                 )173                 .unwrap();174         }175         let _ = out.emit("text", "text/plain; charset=utf-8", b"ok");176         Ok(Report::default())177     }178 }179 180 fn read(file: &CacheFile) -> Vec<u8> {181     let mut file = std::fs::File::from(file.file.try_clone().unwrap());182     let mut bytes = Vec::new();183     file.read_to_end(&mut bytes).unwrap();184     bytes185 }186 187 fn write_bytes(write: &CacheWrite) {188     let mut file = std::fs::File::from(write.file.try_clone().unwrap());189     file.write_all(PAYLOAD).unwrap();190     file.sync_all().unwrap();191 }192 193 fn config(dir: &std::path::Path) -> CacheConfig {194     CacheConfig {195         enabled: true,196         persist: Persist::Reboot,197         pin_bound: 0,198         flush_budget: Duration::from_secs(1),199         default_ttl: Duration::from_secs(3600),200         classes: BTreeMap::new(),201         tiers: vec![TierConfig {202             name: "wire".into(),203             dir: dir.to_path_buf(),204             bound: Some(1 << 20),205             headroom: 0,206             ttl: None,207         }],208         blob_dir: std::path::PathBuf::new(),209     }210 }211 212 #[test]213 fn a_plugin_round_trips_a_slot_through_the_core() {214     let base = std::path::Path::new("/dev/shm");215     let dir = base.join(format!(216         "inf3r-wire-cache-{}-{}",217         std::process::id(),218         std::time::SystemTime::now()219             .duration_since(std::time::UNIX_EPOCH)220             .unwrap()221             .as_nanos()222     ));223     let _ = fs::remove_dir_all(&dir);224     fs::create_dir_all(&dir).unwrap();225     fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();226     let config = config(&dir);227     let store = Cache::open(config.clone()).unwrap();228     let runtime = Arc::new(CacheRuntime::new(store.clone(), config));229     let codec = Arc::new(Codec {230         transport: OnceLock::new(),231     });232     let hit = Arc::new(Mutex::new(false));233     let miss = Arc::new(Mutex::new(false));234     let plugin = Arc::new(PluginImpl {235         codec: Arc::clone(&codec),236         hit: Arc::clone(&hit),237         miss: Arc::clone(&miss),238     });239     let (caller, server) = UnixStream::pair().unwrap();240     let served = thread::spawn(move || serve(server, plugin));241     let peer = Peer::connect(caller, "core", Duration::from_secs(2)).unwrap();242     assert_eq!(peer.version(), Some(2));243     let catalogue = peer.catalogue().unwrap();244     let spec = catalogue.cache.clone().expect("cache spec");245     let (session, host) = runtime246         .attach("cache-test", &spec, [9; 32], Duration::from_secs(60), true)247         .unwrap();248     peer.install_cache(session, host);249     peer.load(&Grant { deps: Vec::new() }, Duration::from_secs(2))250         .unwrap();251 252     let open = || inf3r_proto::body::Open {253         request_id: "r".into(),254         model: "cache-test".into(),255         capability: "chat".into(),256         credit: 1024,257         budget_ms: 5000,258         parts: vec![Part {259             kind: PartKind::Text,260             mime: "text/plain".into(),261             role: Some("user".into()),262             len: 2,263             hold: inf3r_proto::body::Hold::Inline(b"hi".to_vec()),264         }],265         params: inf3r_proto::Value::Map(Vec::new()),266     };267     for _ in 0..2 {268         let mut job = peer.open(open(), &[]).unwrap();269         loop {270             match job.next().unwrap() {271                 Some(inf3r_proto::client::Item::Done(_, _)) | None => break,272                 Some(_) => {}273             }274         }275     }276     assert!(*miss.lock().unwrap());277     assert!(*hit.lock().unwrap());278     assert_eq!(store.len(), 1);279     peer.close().unwrap();280     served.join().unwrap().unwrap();281     let _ = fs::remove_dir_all(&dir);282 }