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/adapter.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 / adapter.rs` 418 lines ยท 12835 bytes Raw Blame History 1 //! The bounded asynchronous read adapter. 2 //! 3 //! Rules, in one place: 4 //! 5 //! * `submit` is non-blocking and bounded. It refuses (handing the staging 6 //! buffer back) when the queue depth (`max_in_flight`), the in-flight byte 7 //! budget (`max_inflight_bytes`), the object size bound 8 //! (`max_object_bytes`) or the buffer capacity would be exceeded, when the 9 //! deadline has already passed, or after shutdown. 10 //! * Every accepted read yields exactly one terminal [`ReadCompletion`]: 11 //! `Ready`, `Failed` or `Cancelled`. The staging buffer travels back in it. 12 //! * A read is `Ready` only after the whole object was read, its SHA-256 13 //! compared in constant time with the index digest, and its header matched 14 //! against the requested key and length. Otherwise the buffer is scrubbed 15 //! before it is returned; no partial or unverified bytes are ever visible. 16 //! * Cancellation and the deadline are checked before every chunk and once 17 //! more before the read is marked ready. A single read call that never 18 //! returns cannot be preempted; `chunk_bytes` bounds how long one call can 19 //! delay detection. 20 21 use crate::error::ReadError; 22 use crate::format::{digest_eq, sha256, ArtifactHeader, IndexEntry, ALIGN, HEADER_REGION}; 23 use crate::source::BlockSource; 24 use crate::staging::StagingBuffer; 25 use std::collections::{HashMap, VecDeque}; 26 use std::sync::atomic::{AtomicBool, Ordering}; 27 use std::sync::mpsc::{channel, Receiver, Sender}; 28 use std::sync::{Arc, Condvar, Mutex}; 29 use std::thread::JoinHandle; 30 use std::time::{Duration, Instant}; 31 32 /// Explicit bounds of one adapter. 33 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 34 pub struct ReadLimits { 35 /// Queue depth: reads queued or running at once (also the worker count). 36 pub max_in_flight: usize, 37 /// Sum of the object lengths of reads queued or running. 38 pub max_inflight_bytes: u64, 39 /// Largest object a single read may fetch. 40 pub max_object_bytes: u64, 41 /// Bytes per read call; a 4096 multiple so direct reads stay aligned. 42 pub chunk_bytes: usize, 43 } 44 45 impl Default for ReadLimits { 46 fn default() -> Self { 47 Self { 48 max_in_flight: 4, 49 max_inflight_bytes: 256 << 20, 50 max_object_bytes: 64 << 20, 51 chunk_bytes: 1 << 20, 52 } 53 } 54 } 55 56 /// Never reused within one adapter. 57 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 58 pub struct Ticket(pub u64); 59 60 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 61 pub enum CancelOutcome { 62 /// The read will end `Cancelled` unless it was already verified. 63 Requested, 64 /// No such read is in flight (unknown, or its terminal was already sent). 65 Unknown, 66 } 67 68 /// A verified artifact in its staging buffer. 69 #[derive(Debug)] 70 pub struct ReadyExpert { 71 pub header: ArtifactHeader, 72 pub entry: IndexEntry, 73 buf: StagingBuffer, 74 } 75 76 impl ReadyExpert { 77 /// The FP8 weight bytes, exactly as in the source checkpoint. 78 pub fn weights(&self) -> &[u8] { 79 &self.buf.as_slice()[self.header.weight_range()] 80 } 81 82 /// The scale bytes, exactly as in the source checkpoint. 83 pub fn scales(&self) -> &[u8] { 84 &self.buf.as_slice()[self.header.scale_range()] 85 } 86 87 /// The whole verified artifact. 88 pub fn artifact(&self) -> &[u8] { 89 &self.buf.as_slice()[..self.header.object_len as usize] 90 } 91 92 /// Gives the buffer back for reuse (it still holds the verified bytes). 93 pub fn into_buffer(self) -> StagingBuffer { 94 self.buf 95 } 96 } 97 98 #[derive(Debug)] 99 pub enum Outcome { 100 Ready(ReadyExpert), 101 /// The buffer has been scrubbed. 102 Failed { 103 error: ReadError, 104 buf: StagingBuffer, 105 }, 106 /// The buffer has been scrubbed. 107 Cancelled { 108 buf: StagingBuffer, 109 }, 110 } 111 112 #[derive(Debug)] 113 pub struct ReadCompletion { 114 pub ticket: Ticket, 115 pub outcome: Outcome, 116 pub elapsed: Duration, 117 } 118 119 /// A refused submit: the reason and the caller's buffer, untouched. 120 #[derive(Debug)] 121 pub struct Refused { 122 pub error: ReadError, 123 pub buf: StagingBuffer, 124 } 125 126 struct Job { 127 ticket: Ticket, 128 entry: IndexEntry, 129 deadline: Instant, 130 buf: StagingBuffer, 131 cancel: Arc, 132 submitted: Instant, 133 } 134 135 #[derive(Default)] 136 struct State { 137 queue: VecDeque, 138 in_flight: usize, 139 in_flight_bytes: u64, 140 next_ticket: u64, 141 cancels: HashMap>, 142 shutdown: bool, 143 } 144 145 struct Shared { 146 limits: ReadLimits, 147 source: Arc, 148 state: Mutex, 149 work: Condvar, 150 } 151 152 pub struct ReadAdapter { 153 shared: Arc, 154 workers: Vec>, 155 completions: Mutex>, 156 } 157 158 impl ReadAdapter { 159 /// Starts `limits.max_in_flight` workers over `source`. Limits that are 160 /// zero, or a `chunk_bytes` that is not a 4096 multiple, are refused. 161 pub fn new(source: Arc, limits: ReadLimits) -> Result { 162 if limits.max_in_flight == 0 163 || limits.max_inflight_bytes == 0 164 || limits.max_object_bytes == 0 165 || limits.chunk_bytes == 0 166 || !(limits.chunk_bytes as u64).is_multiple_of(ALIGN) 167 { 168 return Err(ReadError::InvalidLimits); 169 } 170 let shared = Arc::new(Shared { 171 limits, 172 source, 173 state: Mutex::new(State::default()), 174 work: Condvar::new(), 175 }); 176 let (tx, rx) = channel(); 177 let workers = (0..limits.max_in_flight) 178 .map(|_| { 179 let shared = Arc::clone(&shared); 180 let tx: Sender = tx.clone(); 181 std::thread::spawn(move || worker(shared, tx)) 182 }) 183 .collect(); 184 Ok(Self { 185 shared, 186 workers, 187 completions: Mutex::new(rx), 188 }) 189 } 190 191 pub fn limits(&self) -> ReadLimits { 192 self.shared.limits 193 } 194 195 /// Reads queued or running, and their bytes. 196 pub fn in_flight(&self) -> (usize, u64) { 197 let st = self.shared.state.lock().unwrap(); 198 (st.in_flight, st.in_flight_bytes) 199 } 200 201 /// Queues one verified read of `entry` into `buf`. Non-blocking. 202 pub fn submit( 203 &self, 204 entry: IndexEntry, 205 buf: StagingBuffer, 206 deadline: Instant, 207 ) -> Result { 208 let l = &self.shared.limits; 209 let refuse = |error, buf| Err(Refused { error, buf }); 210 let len = entry.object_len; 211 if len <= HEADER_REGION as u64 || !len.is_multiple_of(ALIGN) { 212 return refuse(ReadError::InvalidEntry, buf); 213 } 214 if len > l.max_object_bytes { 215 return refuse(ReadError::ObjectTooLarge, buf); 216 } 217 if len > buf.capacity() as u64 { 218 return refuse( 219 ReadError::InsufficientCapacity { 220 need: len, 221 have: buf.capacity() as u64, 222 }, 223 buf, 224 ); 225 } 226 let now = Instant::now(); 227 if deadline <= now { 228 return refuse(ReadError::DeadlineExceeded, buf); 229 } 230 let mut st = self.shared.state.lock().unwrap(); 231 if st.shutdown { 232 return refuse(ReadError::ShutDown, buf); 233 } 234 if st.in_flight >= l.max_in_flight { 235 return refuse(ReadError::QueueFull, buf); 236 } 237 if st.in_flight_bytes.saturating_add(len) > l.max_inflight_bytes { 238 return refuse(ReadError::InflightBytesExceeded, buf); 239 } 240 let ticket = Ticket(st.next_ticket); 241 st.next_ticket += 1; 242 st.in_flight += 1; 243 st.in_flight_bytes += len; 244 let cancel = Arc::new(AtomicBool::new(false)); 245 st.cancels.insert(ticket.0, Arc::clone(&cancel)); 246 st.queue.push_back(Job { 247 ticket, 248 entry, 249 deadline, 250 buf, 251 cancel, 252 submitted: now, 253 }); 254 drop(st); 255 self.shared.work.notify_one(); 256 Ok(ticket) 257 } 258 259 /// Requests cancellation. Returns immediately; the read still yields its 260 /// one terminal completion. 261 pub fn cancel(&self, ticket: Ticket) -> CancelOutcome { 262 let st = self.shared.state.lock().unwrap(); 263 match st.cancels.get(&ticket.0) { 264 Some(flag) => { 265 flag.store(true, Ordering::SeqCst); 266 CancelOutcome::Requested 267 } 268 None => CancelOutcome::Unknown, 269 } 270 } 271 272 /// Non-blocking: at most `max` completions, oldest first. 273 pub fn poll(&self, max: usize) -> Vec { 274 let rx = self.completions.lock().unwrap(); 275 let mut out = Vec::new(); 276 while out.len() < max { 277 match rx.try_recv() { 278 Ok(c) => out.push(c), 279 Err(_) => break, 280 } 281 } 282 out 283 } 284 285 /// Blocks up to `timeout` for the next completion. 286 pub fn wait(&self, timeout: Duration) -> Option { 287 let rx = self.completions.lock().unwrap(); 288 rx.recv_timeout(timeout).ok() 289 } 290 } 291 292 impl Drop for ReadAdapter { 293 /// Stops intake, cancels every queued and running read and joins the workers. 294 fn drop(&mut self) { 295 { 296 let mut st = self.shared.state.lock().unwrap(); 297 st.shutdown = true; 298 for flag in st.cancels.values() { 299 flag.store(true, Ordering::SeqCst); 300 } 301 } 302 self.shared.work.notify_all(); 303 for w in self.workers.drain(..) { 304 let _ = w.join(); 305 } 306 } 307 } 308 309 fn worker(shared: Arc, tx: Sender) { 310 loop { 311 let job = { 312 let mut st = shared.state.lock().unwrap(); 313 loop { 314 if let Some(job) = st.queue.pop_front() { 315 break job; 316 } 317 if st.shutdown { 318 return; 319 } 320 st = shared.work.wait(st).unwrap(); 321 } 322 }; 323 let ticket = job.ticket; 324 let len = job.entry.object_len; 325 let submitted = job.submitted; 326 let outcome = run(&shared, job); 327 { 328 let mut st = shared.state.lock().unwrap(); 329 st.in_flight -= 1; 330 st.in_flight_bytes -= len; 331 st.cancels.remove(&ticket.0); 332 } 333 // A dropped receiver only means nobody is listening any more. 334 let _ = tx.send(ReadCompletion { 335 ticket, 336 outcome, 337 elapsed: submitted.elapsed(), 338 }); 339 } 340 } 341 342 enum Stop { 343 Error(ReadError), 344 Cancelled, 345 } 346 347 fn run(shared: &Shared, job: Job) -> Outcome { 348 let Job { 349 entry, 350 deadline, 351 mut buf, 352 cancel, 353 .. 354 } = job; 355 match fill_and_verify(shared, &entry, deadline, &cancel, &mut buf) { 356 Ok(header) => Outcome::Ready(ReadyExpert { header, entry, buf }), 357 Err(stop) => { 358 buf.scrub(); 359 match stop { 360 Stop::Cancelled => Outcome::Cancelled { buf }, 361 Stop::Error(error) => Outcome::Failed { error, buf }, 362 } 363 } 364 } 365 } 366 367 fn checkpoint(deadline: Instant, cancel: &AtomicBool) -> Result<(), Stop> { 368 if cancel.load(Ordering::SeqCst) { 369 return Err(Stop::Cancelled); 370 } 371 if Instant::now() >= deadline { 372 return Err(Stop::Error(ReadError::DeadlineExceeded)); 373 } 374 Ok(()) 375 } 376 377 fn fill_and_verify( 378 shared: &Shared, 379 entry: &IndexEntry, 380 deadline: Instant, 381 cancel: &AtomicBool, 382 buf: &mut StagingBuffer, 383 ) -> Result { 384 let e = Stop::Error; 385 checkpoint(deadline, cancel)?; 386 let expected = entry.object_len; 387 let mut reader = shared.source.open(&entry.data_digest).map_err(e)?; 388 let found = reader.size().map_err(e)?; 389 if found != expected { 390 return Err(e(ReadError::LengthMismatch { expected, found })); 391 } 392 let n = expected as usize; 393 let dst = &mut buf.as_mut_slice()[..n]; 394 let mut done = 0usize; 395 while done < n { 396 checkpoint(deadline, cancel)?; 397 let end = (done + shared.limits.chunk_bytes).min(n); 398 let got = reader 399 .read_at(done as u64, &mut dst[done..end]) 400 .map_err(e)?; 401 if got == 0 { 402 return Err(e(ReadError::UnexpectedEof { 403 read: done as u64, 404 expected, 405 })); 406 } 407 done += got.min(end - done); 408 } 409 if !digest_eq(&sha256(dst), &entry.data_digest) { 410 return Err(e(ReadError::DigestMismatch)); 411 } 412 let header = ArtifactHeader::decode(dst).map_err(|_| e(ReadError::HeaderMismatch))?; 413 if header.key != entry.key || header.object_len != expected { 414 return Err(e(ReadError::HeaderMismatch)); 415 } 416 checkpoint(deadline, cancel)?; 417 Ok(header) 418 }