plugins/mock/x64-cpu/src/cache.rs 6.3 KiB 203 lines Raw
1 //! The mock's cache codec.2 //!3 //! The mock has no tensors, so its "slot" is a deterministic block of bytes.4 //! The codec is deliberately small: it proves that a binding can derive a key,5 //! restore through a descriptor, erase on a miss, and survive a crash while a6 //! write lease is open. Fault modes are selected by `INF3R_MOCK_CACHE` so the7 //! conformance runner can exercise the host's abort and timeout paths without8 //! making the normal mock lie.9 10 use std::fs::OpenOptions;11 use std::io::{Read, Write};12 use std::sync::Mutex;13 use std::time::Duration;14 15 use inf3r_plugin_sdk::cache::{CacheCodec, CacheFile, CacheTransport, FlushReport, Reserve};16 use inf3r_proto::body::{CacheEntryKind, CacheSpec, CacheStateKind};17 18 /// The one fake slot.19 pub const SLOT: u32 = 0;20 21 /// The bytes in one fake slot.22 const PAYLOAD: &[u8] = b"inf3r-mock-kv-slot-v1";23 24 /// The codec installed on the mock plugin.25 pub struct MockCache {26     transport: Mutex<Option<std::sync::Arc<dyn CacheTransport>>>,27 }28 29 impl Default for MockCache {30     fn default() -> MockCache {31         MockCache {32             transport: Mutex::new(None),33         }34     }35 }36 37 impl MockCache {38     /// Restores the fake slot for one prompt. A miss erases the slot first;39     /// this is the correctness rule, not an optimization.40     pub fn restore(&self, prompt: &str) -> bool {41         let key = digest(prompt);42         let Some(transport) = self.transport.lock().unwrap().clone() else {43             return false;44         };45         let timeout = Duration::from_secs(2);46         match transport.lookup(&[key], None, timeout) {47             Ok(Some(hit)) => {48                 trace("lookup-hit");49                 if verify(&hit) {50                     trace("restore");51                     let _ = transport.release(hit.lease_id, true, 1);52                     true53                 } else {54                     trace("restore-corrupt");55                     let _ = transport.release(hit.lease_id, false, 1);56                     let _ = self.erase(SLOT);57                     false58                 }59             }60             Ok(None) => {61                 trace("lookup-miss");62                 let _ = self.erase(SLOT);63                 false64             }65             Err(_) => {66                 let _ = self.erase(SLOT);67                 false68             }69         }70     }71 72     /// Saves the fake slot after a completed turn.73     pub fn save(&self, prompt: &str) {74         let key = digest(prompt);75         let Some(transport) = self.transport.lock().unwrap().clone() else {76             return;77         };78         let timeout = Duration::from_secs(2);79         let request = Reserve {80             key,81             lineage: None,82             supersedes: None,83             kind: CacheEntryKind::Tip,84             est_bytes: PAYLOAD.len() as u64,85             prefill_ms: 10,86             token_count: prompt.split_whitespace().count() as u64,87             pin: false,88         };89         let Ok(Some(write)) = transport.reserve(request, timeout) else {90             return;91         };92         trace("reserve");93         let mut file = std::fs::File::from(write.file.try_clone().expect("cache fd"));94         if let Err(why) = file.write_all(PAYLOAD) {95             trace(&format!("save-error: {why}"));96             let _ = transport.commit(write.lease_id, false, 0, 0, 0, 0);97             return;98         }99         if std::env::var("INF3R_MOCK_CACHE").as_deref() == Ok("crash-save") {100             // Leave a live lease and a partial temp behind; the host must101             // abort it when the socket dies.102             std::process::exit(17);103         }104         if let Err(why) = file.sync_all() {105             trace(&format!("save-error: {why}"));106             let _ = transport.commit(write.lease_id, false, 0, 0, 0, 0);107             return;108         }109         let crc = crc32c(PAYLOAD);110         let _ = transport.commit(write.lease_id, true, PAYLOAD.len() as u64, crc, 1, 1);111         trace("commit");112     }113 }114 115 impl CacheCodec for MockCache {116     fn spec(&self) -> CacheSpec {117         CacheSpec {118             codec_version: 1,119             slots: 1,120             state_kind: CacheStateKind::CheckpointExact,121             max_entry_bytes: 1 << 20,122             local_ram_bytes: 0,123             supports_save: true,124             supports_restore: true,125             supports_erase: true,126         }127     }128 129     fn fingerprint(&self) -> [u8; 32] {130         let mut out = [0u8; 32];131         for (index, byte) in PAYLOAD.iter().enumerate() {132             out[index % 32] ^= *byte;133         }134         out135     }136 137     fn attach(&self, transport: std::sync::Arc<dyn CacheTransport>) {138         *self.transport.lock().unwrap() = Some(transport);139     }140 141     fn flush(&self, _budget: Duration) -> FlushReport {142         if std::env::var("INF3R_MOCK_CACHE").as_deref() == Ok("stall-flush") {143             std::thread::sleep(Duration::from_secs(2));144         }145         trace("flush");146         FlushReport::default()147     }148 149     fn erase(&self, _slot: u32) -> std::io::Result<()> {150         trace("erase");151         Ok(())152     }153 }154 155 fn verify(hit: &CacheFile) -> bool {156     let mut file = std::fs::File::from(hit.file.try_clone().expect("cache fd"));157     let mut bytes = Vec::new();158     if file.read_to_end(&mut bytes).is_err()159         || bytes.len() as u64 != hit.bytes160         || crc32c(&bytes) != hit.crc32c161     {162         return false;163     }164     drop(file);165     true166 }167 168 fn digest(text: &str) -> [u8; 32] {169     let mut out = [0u8; 32];170     let mut hash: u64 = 0xcbf2_9ce4_8422_2325;171     for byte in text.as_bytes() {172         hash ^= u64::from(*byte);173         hash = hash.wrapping_mul(0x0000_0100_0000_01b3);174     }175     for (index, chunk) in out.chunks_mut(8).enumerate() {176         let value = hash.rotate_left((index as u32) * 7);177         chunk.copy_from_slice(&value.to_le_bytes()[..chunk.len()]);178     }179     out180 }181 182 fn trace(event: &str) {183     let Ok(path) = std::env::var("INF3R_CACHE_TRACE") else {184         return;185     };186     if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {187         let _ = writeln!(file, "{event}");188     }189 }190 191 /// The small CRC32C the mock uses for its fake slot. It is deliberately local:192 /// a plugin may not link the host's storage engine.193 fn crc32c(bytes: &[u8]) -> u32 {194     let mut crc = !0u32;195     for byte in bytes {196         crc ^= u32::from(*byte);197         for _ in 0..8 {198             let mask = 0u32.wrapping_sub(crc & 1);199             crc = (crc >> 1) ^ (0x82f6_3b78 & mask);200         }201     }202     !crc203 }