interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-heartbeat / src / reader.rs

547 lines · 17672 bytes Raw Blame History
1//! Bounded expert read adapter (Expert Ribbon P1, sc#629): random reads of one selected expert from the
2//! checkpoint shards into a fixed pool of aligned staging buffers, verified against the manifest digest
3//! before anyone can see the bytes.
4//!
5//! * Bounded: `queue_depth` staging buffers, allocated once. `submit` refuses with [`ReadError::QueueFull`]
6//! when all are in use (no unbounded queue, no hidden allocation).
7//! * Verified: a [`VerifiedExpert`] exists only after the whole expert was read and its BLAKE3 matched. A short
8//! read, EOF, I/O error or digest mismatch returns an explicit error and publishes nothing.
9//! * Cancellation and deadlines: [`Ticket::cancel`] and [`Ticket::wait`]'s deadline. A read that is already in
10//! the kernel cannot be interrupted; its result is discarded and the buffer returns to the pool when it ends.
11//! * Shutdown: dropping the adapter closes the queue and joins every worker (outstanding tickets see
12//! [`ReadError::Shutdown`]).
13//! * Device: [`ShardDevice`]. [`FileShards`] is the Linux one (O_DIRECT or buffered, chosen by measurement, see
14//! the README); [`FakeShards`] is a deterministic in-memory one with injectable latency and faults for tests.
15
16use std::collections::VecDeque;
17use std::fs::{File, OpenOptions};
18use std::os::unix::fs::{FileExt, OpenOptionsExt};
19use std::path::PathBuf;
20use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
21use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender};
22use std::sync::{Arc, Condvar, Mutex};
23use std::thread::JoinHandle;
24use std::time::{Duration, Instant};
25
26use crate::aligned::{round_down, round_up, AlignedBuf};
27use crate::layout::Payload;
28use crate::manifest::{ExpertEntry, Manifest};
29
30/// Positional reads from the checkpoint shards.
31pub trait ShardDevice: Send + Sync {
32 fn read_at(&self, shard: u32, buf: &mut [u8], off: u64) -> std::io::Result<usize>;
33 /// Alignment of buffers, offsets and lengths the device needs (4096 for O_DIRECT, 1 otherwise).
34 fn align(&self) -> usize;
35}
36
37/// The shard files, read-only, O_DIRECT or buffered.
38pub struct FileShards {
39 files: Vec<File>,
40 direct: bool,
41}
42
43impl FileShards {
44 pub fn open(paths: &[PathBuf], direct: bool) -> Result<Self, ReadError> {
45 let mut files = Vec::with_capacity(paths.len());
46 for p in paths {
47 let mut o = OpenOptions::new();
48 o.read(true);
49 if direct {
50 o.custom_flags(libc::O_DIRECT);
51 }
52 files.push(
53 o.open(p)
54 .map_err(|e| ReadError::Io(format!("open {}: {e}", p.display())))?,
55 );
56 }
57 Ok(Self { files, direct })
58 }
59}
60
61impl ShardDevice for FileShards {
62 fn read_at(&self, shard: u32, buf: &mut [u8], off: u64) -> std::io::Result<usize> {
63 let f = self
64 .files
65 .get(shard as usize)
66 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "shard index"))?;
67 f.read_at(buf, off)
68 }
69 fn align(&self) -> usize {
70 if self.direct {
71 crate::IO_ALIGN
72 } else {
73 1
74 }
75 }
76}
77
78/// A fault the fake device applies to one read call (counted from 0 over the device's life).
79#[derive(Debug)]
80pub enum Fault {
81 /// The call returns EIO.
82 Eio,
83 /// The call returns at most this many bytes, then every later call on the same request returns 0 (EOF).
84 Short(usize),
85 /// The call succeeds but flips one byte of what it returns.
86 Flip,
87 /// The call blocks until the sender is dropped or sends (a stalled NVMe), then reads normally.
88 Stall(Receiver<()>),
89}
90
91/// Deterministic in-memory shards for tests: optional fixed latency per read and a fault plan by call index.
92pub struct FakeShards {
93 pub shards: Vec<Vec<u8>>,
94 pub latency: Duration,
95 faults: Mutex<VecDeque<(u64, Fault)>>,
96 calls: AtomicU64,
97 eof_after_short: Mutex<Option<u64>>,
98}
99
100impl FakeShards {
101 pub fn new(shards: Vec<Vec<u8>>, latency: Duration) -> Self {
102 Self {
103 shards,
104 latency,
105 faults: Mutex::new(VecDeque::new()),
106 calls: AtomicU64::new(0),
107 eof_after_short: Mutex::new(None),
108 }
109 }
110 /// Apply `f` to read call number `call` (0-based over the device's life).
111 pub fn fault_at(&self, call: u64, f: Fault) {
112 self.faults.lock().unwrap().push_back((call, f));
113 }
114 pub fn calls(&self) -> u64 {
115 self.calls.load(Ordering::Relaxed)
116 }
117}
118
119impl ShardDevice for FakeShards {
120 fn read_at(&self, shard: u32, buf: &mut [u8], off: u64) -> std::io::Result<usize> {
121 let call = self.calls.fetch_add(1, Ordering::Relaxed);
122 if !self.latency.is_zero() {
123 std::thread::sleep(self.latency);
124 }
125 if let Some(c) = *self.eof_after_short.lock().unwrap() {
126 if call == c + 1 {
127 return Ok(0);
128 }
129 }
130 let fault = {
131 let mut q = self.faults.lock().unwrap();
132 q.iter()
133 .position(|(c, _)| *c == call)
134 .and_then(|i| q.remove(i))
135 .map(|(_, f)| f)
136 };
137 let data = &self.shards[shard as usize];
138 let start = (off as usize).min(data.len());
139 let mut n = buf.len().min(data.len() - start);
140 match fault {
141 Some(Fault::Eio) => return Err(std::io::Error::from_raw_os_error(libc::EIO)),
142 Some(Fault::Short(m)) => {
143 n = n.min(m);
144 *self.eof_after_short.lock().unwrap() = Some(call);
145 }
146 Some(Fault::Stall(ref rx)) => {
147 let _ = rx.recv();
148 }
149 _ => {}
150 }
151 buf[..n].copy_from_slice(&data[start..start + n]);
152 if let (Some(Fault::Flip), true) = (&fault, n > 0) {
153 buf[n / 2] ^= 0x5A;
154 }
155 Ok(n)
156 }
157 fn align(&self) -> usize {
158 1
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum ReadError {
164 /// Every staging buffer is in use (bounded queue).
165 QueueFull,
166 /// The expert does not fit one staging buffer.
167 TooLarge {
168 need: usize,
169 cap: usize,
170 },
171 Io(String),
172 /// Fewer bytes than the manifest span (EOF or a short read that never completed).
173 ShortRead {
174 expert: (u16, u16),
175 wanted: usize,
176 got: usize,
177 },
178 DigestMismatch {
179 expert: (u16, u16),
180 },
181 Cancelled,
182 /// The waiter's deadline passed before the read finished (a stalled read).
183 Deadline,
184 Shutdown,
185 Manifest(String),
186}
187
188impl std::fmt::Display for ReadError {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190 write!(f, "{self:?}")
191 }
192}
193impl std::error::Error for ReadError {}
194
195#[derive(Debug, Clone, Copy)]
196pub struct ReadConfig {
197 /// Reader threads (parallel reads in flight).
198 pub workers: usize,
199 /// Staging buffers = the most requests in flight or waiting to be consumed.
200 pub queue_depth: usize,
201}
202
203#[derive(Debug, Clone, Default)]
204pub struct ReadStats {
205 /// Successfully queued jobs, observable when submit returns.
206 pub reads_submitted: u64,
207 pub reads_ok: u64,
208 pub payload_bytes: u64,
209 pub device_bytes: u64,
210 pub read_ns: u64,
211 pub digest_ns: u64,
212 pub errors: u64,
213 pub queue_full: u64,
214}
215
216struct Pool {
217 bufs: Mutex<Vec<AlignedBuf>>,
218 returned: Condvar,
219 cap: usize,
220}
221
222impl Pool {
223 fn give_back(&self, b: AlignedBuf) {
224 self.bufs.lock().unwrap().push(b);
225 self.returned.notify_all();
226 }
227}
228
229/// A whole, digest-checked expert in a staging buffer. The buffer returns to the pool on drop.
230pub struct VerifiedExpert {
231 pub index: usize,
232 pub layer: u16,
233 pub expert: u16,
234 buf: Option<AlignedBuf>,
235 ranges: Vec<(usize, usize)>,
236 pool: Arc<Pool>,
237}
238
239impl VerifiedExpert {
240 pub fn payload(&self) -> Payload<'_> {
241 let b = self.buf.as_ref().expect("buffer").as_slice();
242 Payload::new(self.ranges.iter().map(|&(o, l)| &b[o..o + l]).collect())
243 }
244}
245
246impl Drop for VerifiedExpert {
247 fn drop(&mut self) {
248 if let Some(b) = self.buf.take() {
249 self.pool.give_back(b);
250 }
251 }
252}
253
254type Reply = Result<VerifiedExpert, ReadError>;
255
256struct Job {
257 index: usize,
258 buf: AlignedBuf,
259 cancel: Arc<AtomicBool>,
260 reply: SyncSender<Reply>,
261}
262
263/// One submitted read.
264pub struct Ticket {
265 rx: Receiver<Reply>,
266 cancel: Arc<AtomicBool>,
267}
268
269impl Ticket {
270 /// Poll the existing worker without blocking the consumer's GPU work.
271 pub fn try_wait(&self) -> Result<Option<VerifiedExpert>, ReadError> {
272 match self.rx.try_recv() {
273 Ok(result) => result.map(Some),
274 Err(mpsc::TryRecvError::Empty) => Ok(None),
275 Err(mpsc::TryRecvError::Disconnected) => Err(ReadError::Shutdown),
276 }
277 }
278 /// Request cancellation: a read not yet started is skipped; one in progress is discarded.
279 pub fn cancel(&self) {
280 self.cancel.store(true, Ordering::Release);
281 }
282 /// Wait up to `deadline` for the verified expert. On timeout the request is cancelled.
283 pub fn wait(self, deadline: Duration) -> Result<VerifiedExpert, ReadError> {
284 match self.rx.recv_timeout(deadline) {
285 Ok(r) => r,
286 Err(RecvTimeoutError::Timeout) => {
287 self.cancel();
288 Err(ReadError::Deadline)
289 }
290 Err(RecvTimeoutError::Disconnected) => Err(ReadError::Shutdown),
291 }
292 }
293}
294
295pub struct ReadAdapter {
296 manifest: Arc<Manifest>,
297 pool: Arc<Pool>,
298 tx: Option<SyncSender<Job>>,
299 workers: Vec<JoinHandle<()>>,
300 stats: Arc<Mutex<ReadStats>>,
301 queue_depth: usize,
302}
303
304/// Bytes one staging buffer needs for any expert of `m` on a device of alignment `align`.
305pub fn staging_bytes(m: &Manifest, align: usize) -> usize {
306 m.experts
307 .iter()
308 .map(|e| {
309 e.segments
310 .iter()
311 .map(|s| round_up(s.len as usize + align, align.max(crate::IO_ALIGN)))
312 .sum::<usize>()
313 })
314 .max()
315 .unwrap_or(crate::IO_ALIGN)
316}
317
318impl ReadAdapter {
319 pub fn new(manifest: Arc<Manifest>, dev: Arc<dyn ShardDevice>, cfg: ReadConfig) -> Self {
320 assert!(cfg.workers > 0 && cfg.queue_depth > 0);
321 let cap = staging_bytes(&manifest, dev.align());
322 let pool = Arc::new(Pool {
323 bufs: Mutex::new((0..cfg.queue_depth).map(|_| AlignedBuf::new(cap)).collect()),
324 returned: Condvar::new(),
325 cap,
326 });
327 let (tx, rx) = mpsc::sync_channel::<Job>(cfg.queue_depth);
328 let rx = Arc::new(Mutex::new(rx));
329 let stats = Arc::new(Mutex::new(ReadStats::default()));
330 let workers = (0..cfg.workers)
331 .map(|_| {
332 let (rx, dev, m, pool, stats) = (
333 rx.clone(),
334 dev.clone(),
335 manifest.clone(),
336 pool.clone(),
337 stats.clone(),
338 );
339 std::thread::spawn(move || loop {
340 let job = match rx.lock().unwrap().recv() {
341 Ok(j) => j,
342 Err(_) => return,
343 };
344 let r = run_job(&*dev, &m, &pool, &stats, job.index, job.buf, &job.cancel);
345 // A waiter that gave up (deadline) dropped its receiver: the buffer comes back via drop.
346 let _ = job.reply.send(r);
347 })
348 })
349 .collect();
350 Self {
351 manifest,
352 pool,
353 tx: Some(tx),
354 workers,
355 stats,
356 queue_depth: cfg.queue_depth,
357 }
358 }
359
360 pub fn manifest(&self) -> &Manifest {
361 &self.manifest
362 }
363
364 pub fn staging_capacity(&self) -> usize {
365 self.pool.cap
366 }
367
368 pub fn queue_depth(&self) -> usize {
369 self.queue_depth
370 }
371
372 pub fn stats(&self) -> ReadStats {
373 self.stats.lock().unwrap().clone()
374 }
375
376 /// Queue a read of `manifest.experts[index]`. Refuses (QueueFull) when every staging buffer is in use.
377 pub fn submit(&self, index: usize) -> Result<Ticket, ReadError> {
378 if index >= self.manifest.experts.len() {
379 return Err(ReadError::Manifest(format!("expert index {index}")));
380 }
381 let buf = match self.pool.bufs.lock().unwrap().pop() {
382 Some(b) => b,
383 None => {
384 self.stats.lock().unwrap().queue_full += 1;
385 return Err(ReadError::QueueFull);
386 }
387 };
388 let (rtx, rrx) = mpsc::sync_channel(1);
389 let cancel = Arc::new(AtomicBool::new(false));
390 let job = Job {
391 index,
392 buf,
393 cancel: cancel.clone(),
394 reply: rtx,
395 };
396 let tx = self.tx.as_ref().ok_or(ReadError::Shutdown)?;
397 if let Err(mpsc::SendError(j)) = tx.send(job) {
398 self.pool.give_back(j.buf);
399 return Err(ReadError::Shutdown);
400 }
401 self.stats.lock().unwrap().reads_submitted += 1;
402 Ok(Ticket { rx: rrx, cancel })
403 }
404
405 /// Submit, waiting (up to `wait`) for a free staging buffer instead of refusing.
406 pub fn submit_wait(&self, index: usize, wait: Duration) -> Result<Ticket, ReadError> {
407 let t0 = Instant::now();
408 loop {
409 match self.submit(index) {
410 Err(ReadError::QueueFull) => {
411 let left = wait.saturating_sub(t0.elapsed());
412 if left.is_zero() {
413 return Err(ReadError::QueueFull);
414 }
415 let g = self.pool.bufs.lock().unwrap();
416 if g.is_empty() {
417 let _ = self.pool.returned.wait_timeout(g, left).unwrap();
418 }
419 }
420 r => return r,
421 }
422 }
423 }
424}
425
426impl Drop for ReadAdapter {
427 fn drop(&mut self) {
428 self.tx.take();
429 for w in self.workers.drain(..) {
430 let _ = w.join();
431 }
432 }
433}
434
435fn run_job(
436 dev: &dyn ShardDevice,
437 m: &Manifest,
438 pool: &Arc<Pool>,
439 stats: &Mutex<ReadStats>,
440 index: usize,
441 mut buf: AlignedBuf,
442 cancel: &AtomicBool,
443) -> Reply {
444 let e = &m.experts[index];
445 let fail = |buf: AlignedBuf, err: ReadError| {
446 pool.give_back(buf);
447 if err != ReadError::Cancelled {
448 stats.lock().unwrap().errors += 1;
449 }
450 Err(err)
451 };
452 if cancel.load(Ordering::Acquire) {
453 return fail(buf, ReadError::Cancelled);
454 }
455 let t0 = Instant::now();
456 let (ranges, device) = match read_expert(dev, e, buf.as_mut_slice()) {
457 Ok(v) => v,
458 Err(err) => return fail(buf, err),
459 };
460 let read_ns = t0.elapsed().as_nanos() as u64;
461 if cancel.load(Ordering::Acquire) {
462 return fail(buf, ReadError::Cancelled);
463 }
464 let t1 = Instant::now();
465 let expected = match e.digest_bytes() {
466 Ok(d) => d,
467 Err(err) => return fail(buf, ReadError::Manifest(err.to_string())),
468 };
469 let mut h = blake3::Hasher::new();
470 for &(o, l) in &ranges {
471 h.update(&buf.as_slice()[o..o + l]);
472 }
473 if h.finalize().as_bytes() != &expected {
474 return fail(
475 buf,
476 ReadError::DigestMismatch {
477 expert: (e.layer, e.expert),
478 },
479 );
480 }
481 {
482 let mut s = stats.lock().unwrap();
483 s.reads_ok += 1;
484 s.payload_bytes += e.len;
485 s.device_bytes += device;
486 s.read_ns += read_ns;
487 s.digest_ns += t1.elapsed().as_nanos() as u64;
488 }
489 Ok(VerifiedExpert {
490 index,
491 layer: e.layer,
492 expert: e.expert,
493 buf: Some(buf),
494 ranges,
495 pool: pool.clone(),
496 })
497}
498
499/// Reads every segment of `e` into its own aligned window of `buf`. Returns the payload ranges and the device bytes.
500pub fn read_expert(
501 dev: &dyn ShardDevice,
502 e: &ExpertEntry,
503 buf: &mut [u8],
504) -> Result<(Vec<(usize, usize)>, u64), ReadError> {
505 let align = dev.align().max(1);
506 let window_align = align.max(crate::IO_ALIGN);
507 let mut ranges = Vec::with_capacity(e.segments.len());
508 let (mut base, mut device) = (0usize, 0u64);
509 for seg in &e.segments {
510 let astart = round_down(seg.start, align as u64);
511 let off = (seg.start - astart) as usize;
512 let need = off + seg.len as usize;
513 let window = round_up(need, align);
514 if base + window > buf.len() {
515 return Err(ReadError::TooLarge {
516 need: base + window,
517 cap: buf.len(),
518 });
519 }
520 let w = &mut buf[base..base + window];
521 let mut got = 0usize;
522 while got < need {
523 match dev.read_at(seg.shard, &mut w[got..], astart + got as u64) {
524 Ok(0) => break,
525 Ok(n) => got += n,
526 Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {}
527 Err(err) => {
528 return Err(ReadError::Io(format!(
529 "read expert ({},{}): {err}",
530 e.layer, e.expert
531 )))
532 }
533 }
534 }
535 if got < need {
536 return Err(ReadError::ShortRead {
537 expert: (e.layer, e.expert),
538 wanted: need,
539 got,
540 });
541 }
542 ranges.push((base + off, seg.len as usize));
543 device += got as u64;
544 base += round_up(window, window_align);
545 }
546 Ok((ranges, device))
547}