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 / ring.rs

458 lines · 14061 bytes Raw Blame History
1//! Fixed versioned slots with publish/lease ordering.
2//!
3//! Slot life cycle: `Empty -> Filling -> Published -> Filling -> ...`.
4//! * `begin_fill` waits until no reader holds a lease, then hides the slot
5//! (readers cannot lease a `Filling` slot) and hands out exclusive write
6//! access.
7//! * `FillGuard::publish` hashes the payload and compares against the
8//! expected digest; only on a match does the slot become `Published` with a
9//! fresh ring-wide version.
10//! * Any failure marks the slot `Poisoned` and the whole ring failed: every
11//! later `begin_fill` and `lease` returns [`HeartbeatError::RingFailed`].
12
13use std::cell::UnsafeCell;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use std::sync::{Condvar, Mutex, MutexGuard};
16use std::time::{Duration, Instant};
17
18use crate::aligned::AlignedBuf;
19use crate::error::HeartbeatError;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct SlotTag {
23 pub layer: u16,
24 pub expert: u16,
25 pub version: u64,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29enum Phase {
30 Empty,
31 Filling,
32 Published,
33 Poisoned,
34}
35
36#[derive(Debug)]
37struct SlotState {
38 phase: Phase,
39 tag: Option<SlotTag>,
40 leases: u32,
41 /// Payload ranges (offset, len) in the slot buffer, in payload order.
42 ranges: Vec<(usize, usize)>,
43}
44
45struct Slot {
46 buf: UnsafeCell<AlignedBuf>,
47 state: Mutex<SlotState>,
48 released: Condvar,
49}
50
51// SAFETY: `buf` is written only by the holder of the unique FillGuard while
52// phase == Filling (no leases can exist then), and read only through a Lease
53// while phase == Published (no FillGuard can exist then). Both transitions are
54// made under `state`'s mutex.
55unsafe impl Sync for Slot {}
56
57pub struct Ring {
58 slots: Vec<Slot>,
59 failed: AtomicBool,
60 next_version: AtomicU64,
61}
62
63fn lock(m: &Mutex<SlotState>) -> MutexGuard<'_, SlotState> {
64 // A panicking holder poisons the mutex; treat state as still usable since
65 // the ring's failure flag is the authority.
66 m.lock().unwrap_or_else(|p| p.into_inner())
67}
68
69impl Ring {
70 pub fn new(num_slots: usize, slot_bytes: usize) -> Self {
71 let slots = (0..num_slots)
72 .map(|_| Slot {
73 buf: UnsafeCell::new(AlignedBuf::new(slot_bytes)),
74 state: Mutex::new(SlotState {
75 phase: Phase::Empty,
76 tag: None,
77 leases: 0,
78 ranges: Vec::new(),
79 }),
80 released: Condvar::new(),
81 })
82 .collect();
83 Self {
84 slots,
85 failed: AtomicBool::new(false),
86 next_version: AtomicU64::new(1),
87 }
88 }
89
90 pub fn num_slots(&self) -> usize {
91 self.slots.len()
92 }
93
94 pub fn slot_capacity(&self) -> usize {
95 // SAFETY: capacity is immutable after construction.
96 unsafe { (*self.slots[0].buf.get()).len() }
97 }
98
99 pub fn is_failed(&self) -> bool {
100 self.failed.load(Ordering::Acquire)
101 }
102
103 /// Mark the ring failed (fail closed) and wake every waiter.
104 pub fn fail(&self) {
105 self.failed.store(true, Ordering::Release);
106 for s in &self.slots {
107 let _g = lock(&s.state);
108 s.released.notify_all();
109 }
110 }
111
112 /// Current tag of a slot if it is published.
113 pub fn tag(&self, slot: usize) -> Option<SlotTag> {
114 let st = lock(&self.slots[slot].state);
115 (st.phase == Phase::Published).then_some(st.tag).flatten()
116 }
117
118 /// Lease the published slot holding `(layer, expert)`, if any.
119 pub fn lease(&self, layer: u16, expert: u16) -> Result<Option<Lease<'_>>, HeartbeatError> {
120 if self.is_failed() {
121 return Err(HeartbeatError::RingFailed);
122 }
123 for (i, s) in self.slots.iter().enumerate() {
124 let mut st = lock(&s.state);
125 if st.phase == Phase::Published {
126 if let Some(tag) = st.tag {
127 if tag.layer == layer && tag.expert == expert {
128 st.leases += 1;
129 return Ok(Some(Lease {
130 ring: self,
131 slot: i,
132 tag,
133 ranges: st.ranges.clone(),
134 }));
135 }
136 }
137 }
138 }
139 Ok(None)
140 }
141
142 /// Take exclusive write access to `slot`, waiting (up to `wait`) for
143 /// readers to drop their leases. Returns the time spent waiting.
144 pub fn begin_fill(
145 &self,
146 slot: usize,
147 wait: Duration,
148 ) -> Result<(FillGuard<'_>, Duration), HeartbeatError> {
149 let s = &self.slots[slot];
150 let t0 = Instant::now();
151 let mut st = lock(&s.state);
152 loop {
153 if self.is_failed() || st.phase == Phase::Poisoned {
154 return Err(HeartbeatError::RingFailed);
155 }
156 if st.phase == Phase::Filling {
157 return Err(HeartbeatError::SlotBusy(slot));
158 }
159 if st.leases == 0 {
160 break;
161 }
162 let left = wait.saturating_sub(t0.elapsed());
163 if left.is_zero() {
164 return Err(HeartbeatError::SlotBusy(slot));
165 }
166 st = s
167 .released
168 .wait_timeout(st, left)
169 .unwrap_or_else(|p| p.into_inner())
170 .0;
171 }
172 st.phase = Phase::Filling;
173 st.tag = None;
174 drop(st);
175 Ok((
176 FillGuard {
177 ring: self,
178 slot,
179 done: false,
180 },
181 t0.elapsed(),
182 ))
183 }
184}
185
186/// Exclusive write access to one slot. Dropping it without publishing returns
187/// the slot to `Empty`; [`FillGuard::fail`] poisons the ring.
188pub struct FillGuard<'r> {
189 ring: &'r Ring,
190 slot: usize,
191 done: bool,
192}
193
194impl FillGuard<'_> {
195 pub fn slot(&self) -> usize {
196 self.slot
197 }
198
199 pub fn buf_mut(&mut self) -> &mut [u8] {
200 // SAFETY: phase == Filling and this guard is the unique writer.
201 unsafe { (*self.ring.slots[self.slot].buf.get()).as_mut_slice() }
202 }
203
204 /// Verify BLAKE3 over `ranges` (in order) == expected, then publish. On
205 /// mismatch or a bad range the ring fails closed. Returns the digest time.
206 pub fn publish(
207 mut self,
208 layer: u16,
209 expert: u16,
210 ranges: &[(usize, usize)],
211 expected: &[u8; 32],
212 ) -> Result<(SlotTag, Duration), HeartbeatError> {
213 let cap = self.buf_mut().len();
214 for &(off, len) in ranges {
215 if off.checked_add(len).is_none_or(|end| end > cap) {
216 self.fail_inner();
217 return Err(HeartbeatError::PayloadTooLarge {
218 slot: self.slot,
219 need: off.saturating_add(len),
220 cap,
221 });
222 }
223 }
224 let t0 = Instant::now();
225 let ok = {
226 let buf = &self.buf_mut()[..];
227 let mut h = blake3::Hasher::new();
228 for &(off, len) in ranges {
229 h.update(&buf[off..off + len]);
230 }
231 h.finalize().as_bytes() == expected
232 };
233 let dt = t0.elapsed();
234 if !ok || self.ring.is_failed() {
235 self.fail_inner();
236 return Err(if ok {
237 HeartbeatError::RingFailed
238 } else {
239 HeartbeatError::DigestMismatch {
240 expert: (layer, expert),
241 }
242 });
243 }
244 let version = self.ring.next_version.fetch_add(1, Ordering::AcqRel);
245 let tag = SlotTag {
246 layer,
247 expert,
248 version,
249 };
250 let s = &self.ring.slots[self.slot];
251 let mut st = lock(&s.state);
252 st.phase = Phase::Published;
253 st.tag = Some(tag);
254 st.ranges = ranges.to_vec();
255 drop(st);
256 self.done = true;
257 Ok((tag, dt))
258 }
259
260 /// Release without publishing (slot becomes Empty, not visible).
261 pub fn discard(mut self) {
262 let mut st = lock(&self.ring.slots[self.slot].state);
263 st.phase = Phase::Empty;
264 drop(st);
265 self.done = true;
266 }
267
268 /// Poison this slot and fail the ring closed.
269 pub fn fail(mut self) {
270 self.fail_inner();
271 }
272
273 fn fail_inner(&mut self) {
274 {
275 let mut st = lock(&self.ring.slots[self.slot].state);
276 st.phase = Phase::Poisoned;
277 st.tag = None;
278 }
279 self.done = true;
280 self.ring.fail();
281 }
282}
283
284impl Drop for FillGuard<'_> {
285 fn drop(&mut self) {
286 if !self.done {
287 // Unwinding mid-fill: never publish, fail closed.
288 self.fail_inner();
289 }
290 }
291}
292
293/// Read access to a published slot; the slot cannot be refilled while any
294/// lease is alive.
295pub struct Lease<'r> {
296 ring: &'r Ring,
297 slot: usize,
298 tag: SlotTag,
299 ranges: Vec<(usize, usize)>,
300}
301
302impl Lease<'_> {
303 pub fn tag(&self) -> SlotTag {
304 self.tag
305 }
306
307 pub fn slot(&self) -> usize {
308 self.slot
309 }
310
311 /// Payload pieces in order (one per manifest segment).
312 pub fn segments(&self) -> impl Iterator<Item = &[u8]> + '_ {
313 // SAFETY: leases > 0 keeps phase == Published, so no writer exists.
314 let buf = unsafe { &*self.ring.slots[self.slot].buf.get() }.as_slice();
315 self.ranges.iter().map(move |&(o, l)| &buf[o..o + l])
316 }
317
318 /// Payload copied into one contiguous vector.
319 pub fn to_vec(&self) -> Vec<u8> {
320 self.segments().flatten().copied().collect()
321 }
322}
323
324impl Drop for Lease<'_> {
325 fn drop(&mut self) {
326 let s = &self.ring.slots[self.slot];
327 let mut st = lock(&s.state);
328 st.leases -= 1;
329 if st.leases == 0 {
330 s.released.notify_all();
331 }
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use std::sync::Arc;
339
340 fn fill(ring: &Ring, slot: usize, layer: u16, expert: u16, byte: u8) -> SlotTag {
341 let (mut g, _) = ring.begin_fill(slot, Duration::from_secs(1)).unwrap();
342 g.buf_mut()[..16].fill(byte);
343 let d = *blake3::hash(&[byte; 16]).as_bytes();
344 g.publish(layer, expert, &[(0, 16)], &d).unwrap().0
345 }
346
347 #[test]
348 fn not_visible_until_published() {
349 let ring = Ring::new(2, 4096);
350 let (mut g, _) = ring.begin_fill(0, Duration::ZERO).unwrap();
351 g.buf_mut()[..16].fill(7);
352 assert!(ring.lease(0, 3).unwrap().is_none());
353 let d = *blake3::hash(&[7u8; 16]).as_bytes();
354 let (tag, _) = g.publish(0, 3, &[(0, 16)], &d).unwrap();
355 let l = ring.lease(0, 3).unwrap().unwrap();
356 assert_eq!(l.tag(), tag);
357 assert_eq!(l.to_vec(), vec![7u8; 16]);
358 }
359
360 #[test]
361 fn versions_increase_monotonically() {
362 let ring = Ring::new(1, 4096);
363 let a = fill(&ring, 0, 0, 1, 1);
364 let b = fill(&ring, 0, 0, 2, 2);
365 assert!(b.version > a.version);
366 assert!(
367 ring.lease(0, 1).unwrap().is_none(),
368 "old tag retired on refill"
369 );
370 }
371
372 #[test]
373 fn leased_slot_is_never_overwritten() {
374 let ring = Ring::new(1, 4096);
375 fill(&ring, 0, 1, 1, 9);
376 let l = ring.lease(1, 1).unwrap().unwrap();
377 assert!(matches!(
378 ring.begin_fill(0, Duration::from_millis(20)),
379 Err(HeartbeatError::SlotBusy(0))
380 ));
381 assert_eq!(l.to_vec(), vec![9u8; 16]);
382 drop(l);
383 assert!(ring.begin_fill(0, Duration::ZERO).is_ok());
384 }
385
386 #[test]
387 fn writer_waits_for_lease_release() {
388 let ring = Arc::new(Ring::new(1, 4096));
389 fill(&ring, 0, 1, 1, 9);
390 let r2 = ring.clone();
391 let reader = std::thread::spawn(move || {
392 let l = r2.lease(1, 1).unwrap().unwrap();
393 std::thread::sleep(Duration::from_millis(50));
394 let v = l.to_vec();
395 drop(l);
396 v
397 });
398 std::thread::sleep(Duration::from_millis(10));
399 let (g, waited) = ring.begin_fill(0, Duration::from_secs(5)).unwrap();
400 assert!(waited >= Duration::from_millis(20));
401 g.discard();
402 assert_eq!(reader.join().unwrap(), vec![9u8; 16]);
403 }
404
405 #[test]
406 fn filling_slot_cannot_be_leased_or_double_filled() {
407 let ring = Ring::new(1, 4096);
408 fill(&ring, 0, 0, 0, 1);
409 let (g, _) = ring.begin_fill(0, Duration::ZERO).unwrap();
410 assert!(ring.lease(0, 0).unwrap().is_none());
411 assert!(matches!(
412 ring.begin_fill(0, Duration::ZERO),
413 Err(HeartbeatError::SlotBusy(0))
414 ));
415 g.discard();
416 }
417
418 #[test]
419 fn digest_mismatch_fails_closed() {
420 let ring = Ring::new(2, 4096);
421 fill(&ring, 1, 0, 5, 3);
422 let (mut g, _) = ring.begin_fill(0, Duration::ZERO).unwrap();
423 g.buf_mut()[..16].fill(1);
424 let wrong = *blake3::hash(&[2u8; 16]).as_bytes();
425 assert!(matches!(
426 g.publish(0, 0, &[(0, 16)], &wrong),
427 Err(HeartbeatError::DigestMismatch { .. })
428 ));
429 assert!(ring.is_failed());
430 assert!(matches!(ring.lease(0, 5), Err(HeartbeatError::RingFailed)));
431 assert!(matches!(
432 ring.begin_fill(1, Duration::ZERO),
433 Err(HeartbeatError::RingFailed)
434 ));
435 assert!(ring.tag(0).is_none());
436 }
437
438 #[test]
439 fn oversized_payload_fails_closed() {
440 let ring = Ring::new(1, 4096);
441 let (g, _) = ring.begin_fill(0, Duration::ZERO).unwrap();
442 assert!(matches!(
443 g.publish(0, 0, &[(4000, 200)], &[0; 32]),
444 Err(HeartbeatError::PayloadTooLarge { .. })
445 ));
446 assert!(ring.is_failed());
447 }
448
449 #[test]
450 fn dropped_guard_fails_closed() {
451 let ring = Ring::new(1, 4096);
452 {
453 let _g = ring.begin_fill(0, Duration::ZERO).unwrap();
454 // dropped without publish/discard (e.g. unwinding)
455 }
456 assert!(ring.is_failed());
457 }
458}