Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-expert-store/src/fake.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-expert-store / src / fake.rs` 167 lines ยท 4968 bytes Raw Blame History 1 //! A tiny deterministic in-memory [`BlockSource`] with injectable faults, for 2 //! concurrency, latency, failure, corruption and cancellation tests. No 3 //! randomness, no device access. 4 5 use crate::error::ReadError; 6 use crate::source::{BlockReader, BlockSource}; 7 use std::collections::HashMap; 8 use std::io::ErrorKind; 9 use std::sync::atomic::{AtomicUsize, Ordering}; 10 use std::sync::{Arc, Condvar, Mutex}; 11 use std::time::Duration; 12 13 /// A fault applied to every read of one object. 14 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 15 pub enum Fault { 16 /// XOR 0x01 into the byte at this offset as it is read. 17 CorruptByte(u64), 18 /// The object is this many bytes long (length and data both shortened). 19 Truncate(u64), 20 /// `len` reports the full length but reads return end of file from this offset. 21 EofAt(u64), 22 /// Each read returns at most this many bytes. 23 ShortReads(usize), 24 /// Every read fails with this error kind. 25 IoError(ErrorKind), 26 /// Each read sleeps this long first (a slow or stalled device). 27 Delay(Duration), 28 } 29 30 #[derive(Default)] 31 struct State { 32 objects: HashMap<[u8; 32], Arc>>, 33 faults: HashMap<[u8; 32], Fault>, 34 held: bool, 35 } 36 37 #[derive(Default)] 38 struct Inner { 39 state: Mutex, 40 gate: Condvar, 41 active: AtomicUsize, 42 peak: AtomicUsize, 43 reads: AtomicUsize, 44 } 45 46 /// Cloning shares the same objects, faults and counters. 47 #[derive(Clone, Default)] 48 pub struct FakeSource(Arc); 49 50 impl FakeSource { 51 pub fn new() -> Self { 52 Self::default() 53 } 54 55 pub fn insert(&self, digest: [u8; 32], bytes: Vec) { 56 self.0 57 .state 58 .lock() 59 .unwrap() 60 .objects 61 .insert(digest, Arc::new(bytes)); 62 } 63 64 pub fn set_fault(&self, digest: [u8; 32], fault: Fault) { 65 self.0.state.lock().unwrap().faults.insert(digest, fault); 66 } 67 68 pub fn clear_fault(&self, digest: &[u8; 32]) { 69 self.0.state.lock().unwrap().faults.remove(digest); 70 } 71 72 /// Blocks every read at entry until [`FakeSource::release`]. 73 pub fn hold(&self) { 74 self.0.state.lock().unwrap().held = true; 75 } 76 77 pub fn release(&self) { 78 self.0.state.lock().unwrap().held = false; 79 self.0.gate.notify_all(); 80 } 81 82 /// Reads currently inside `read_at`. 83 pub fn active(&self) -> usize { 84 self.0.active.load(Ordering::SeqCst) 85 } 86 87 /// Most reads ever inside `read_at` at once. 88 pub fn peak(&self) -> usize { 89 self.0.peak.load(Ordering::SeqCst) 90 } 91 92 /// Total `read_at` calls. 93 pub fn reads(&self) -> usize { 94 self.0.reads.load(Ordering::SeqCst) 95 } 96 } 97 98 struct FakeReader { 99 inner: Arc, 100 bytes: Arc>, 101 fault: Option, 102 } 103 104 struct ActiveGuard<'a>(&'a Inner); 105 106 impl Drop for ActiveGuard<'_> { 107 fn drop(&mut self) { 108 self.0.active.fetch_sub(1, Ordering::SeqCst); 109 } 110 } 111 112 impl BlockReader for FakeReader { 113 fn size(&self) -> Result { 114 let full = self.bytes.len() as u64; 115 Ok(match self.fault { 116 Some(Fault::Truncate(n)) => n.min(full), 117 _ => full, 118 }) 119 } 120 121 fn read_at(&mut self, offset: u64, dst: &mut [u8]) -> Result { 122 self.inner.reads.fetch_add(1, Ordering::SeqCst); 123 let now = self.inner.active.fetch_add(1, Ordering::SeqCst) + 1; 124 self.inner.peak.fetch_max(now, Ordering::SeqCst); 125 let _active = ActiveGuard(&self.inner); 126 { 127 let mut st = self.inner.state.lock().unwrap(); 128 while st.held { 129 st = self.inner.gate.wait(st).unwrap(); 130 } 131 } 132 let mut end = self.bytes.len() as u64; 133 let mut max = dst.len(); 134 match self.fault { 135 Some(Fault::IoError(k)) => return Err(ReadError::Io(k)), 136 Some(Fault::Delay(d)) => std::thread::sleep(d), 137 Some(Fault::Truncate(n)) | Some(Fault::EofAt(n)) => end = end.min(n), 138 Some(Fault::ShortReads(n)) => max = max.min(n.max(1)), 139 Some(Fault::CorruptByte(_)) | None => {} 140 } 141 if offset >= end { 142 return Ok(0); 143 } 144 let n = ((end - offset) as usize).min(max); 145 let start = offset as usize; 146 dst[..n].copy_from_slice(&self.bytes[start..start + n]); 147 if let Some(Fault::CorruptByte(at)) = self.fault { 148 if at >= offset && at < offset + n as u64 { 149 dst[(at - offset) as usize] ^= 0x01; 150 } 151 } 152 Ok(n) 153 } 154 } 155 156 impl BlockSource for FakeSource { 157 fn open(&self, digest: &[u8; 32]) -> Result, ReadError> { 158 let st = self.0.state.lock().unwrap(); 159 let bytes = st.objects.get(digest).cloned().ok_or(ReadError::NotFound)?; 160 let fault = st.faults.get(digest).copied(); 161 Ok(Box::new(FakeReader { 162 inner: Arc::clone(&self.0), 163 bytes, 164 fault, 165 })) 166 } 167 }