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

GitHub aien-dev/aien-sovereign-core-mv#159 (code only)

closed derived c70022330e3313da #159

Imported from GitHub aien-dev/aien-sovereign-core-mv#159 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base dd1fe323d5fc774ff0fe6faaadebfea6450563c0 · Head 528f6bee9088bdb728bd20440acd5dba95c30826

Apply it

git checkout -b patch-c70022330e3313da dd1fe323d5fc774ff0fe6faaadebfea6450563c0
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/c70022330e3313da.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
159
528f6bee9088bdb728bd20440acd5dba95c30826
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":159,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/159","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:09Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs
index 66f920ee..cd73fc79 100644
--- a/crates/aien-kv-cache/src/lib.rs
+++ b/crates/aien-kv-cache/src/lib.rs
@@ -176,12 +176,30 @@ impl KvLayout {
             }
         };
 
-        let head_stride_bytes = config.head_dim * element_bytes;
-        let token_stride_bytes = config.num_kv_heads * head_stride_bytes;
-        let kv_plane_stride_bytes = config.block_size * token_stride_bytes;
-        let layer_stride_bytes = 2 * kv_plane_stride_bytes;
-        let block_stride_bytes = config.num_layers * layer_stride_bytes;
-        let total_bytes = config.num_blocks * block_stride_bytes;
+        let overflow = |what: &str| format!("KV layout size overflow computing {what}");
+        let head_stride_bytes = config
+            .head_dim
+            .checked_mul(element_bytes)
+            .ok_or_else(|| overflow("head_stride_bytes"))?;
+        let token_stride_bytes = config
+            .num_kv_heads
+            .checked_mul(head_stride_bytes)
+            .ok_or_else(|| overflow("token_stride_bytes"))?;
+        let kv_plane_stride_bytes = config
+            .block_size
+            .checked_mul(token_stride_bytes)
+            .ok_or_else(|| overflow("kv_plane_stride_bytes"))?;
+        let layer_stride_bytes = kv_plane_stride_bytes
+            .checked_mul(2)
+            .ok_or_else(|| overflow("layer_stride_bytes"))?;
+        let block_stride_bytes = config
+            .num_layers
+            .checked_mul(layer_stride_bytes)
+            .ok_or_else(|| overflow("block_stride_bytes"))?;
+        let total_bytes = config
+            .num_blocks
+            .checked_mul(block_stride_bytes)
+            .ok_or_else(|| overflow("total_bytes"))?;
 
         Ok(Self {
             block_stride_bytes,
@@ -1544,6 +1562,24 @@ mod tests {
         assert_eq!(desc.pool_bytes, (8 * 24576) as u64);
     }
 
+    #[test]
+    fn test_kv_layout_rejects_total_bytes_overflow() {
+        // Formal finding (arch#112): 2^45 blocks wrapped total_bytes to
+        // 6917529027641081856 instead of 25364273101350633472.
+        let cfg = KvPoolConfig {
+            num_blocks: 1usize << 45,
+            block_size: 16,
+            num_layers: 22,
+            num_kv_heads: 4,
+            head_dim: 64,
+            dtype: KvDType::Fp32,
+        };
+        let err = KvLayout::from_config(&cfg).unwrap_err();
+        assert!(err.contains("overflow"), "unexpected error: {err}");
+        assert!(cfg.layout().is_err());
+        assert!(cfg.layout_desc().is_err());
+    }
+
     #[test]
     fn test_kv_layout_independent_address_parity() {
         let cfg = KvPoolConfig::for_tinyllama(16, 16, KvDType::Bf16);
diff --git a/crates/aien-runtime/src/sequence.rs b/crates/aien-runtime/src/sequence.rs
index 51eb2208..bdd6e3f7 100644
--- a/crates/aien-runtime/src/sequence.rs
+++ b/crates/aien-runtime/src/sequence.rs
@@ -62,6 +62,9 @@ pub struct SequenceRecord {
 
 pub struct SequenceSlot {
     pub generation: u32,
+    /// Set when the generation reached u32::MAX and was freed. A retired slot is never reused,
+    /// so a stale id can never match again (same policy as the scheduler arena).
+    pub retired: bool,
     pub record: Option<SequenceRecord>,
 }
 
@@ -71,6 +74,7 @@ pub struct SequenceArena {
     free_slots: Vec<u32>,
     active_count: usize,
     capacity: usize,
+    retired_slots_count: usize,
 }
 
 impl SequenceArena {
@@ -81,6 +85,7 @@ impl SequenceArena {
         for i in 0..capacity {
             slots.push(SequenceSlot {
                 generation: 1,
+                retired: false,
                 record: None,
             });
             free_slots.push(i as u32);
@@ -92,9 +97,25 @@ impl SequenceArena {
             free_slots,
             active_count: 0,
             capacity,
+            retired_slots_count: 0,
         }
     }
 
+    /// Test-only: start every slot at `generation` so the u32::MAX boundary is reachable.
+    #[cfg(test)]
+    pub(crate) fn with_start_generation(capacity: usize, generation: u32) -> Self {
+        let mut arena = Self::new(capacity);
+        for slot in &mut arena.slots {
+            slot.generation = generation;
+        }
+        arena
+    }
+
+    /// Number of slots permanently retired after exhausting their generation space.
+    pub fn retired_slots(&self) -> usize {
+        self.retired_slots_count
+    }
+
     pub fn allocate(
         &mut self,
         world_id: u64,
@@ -198,9 +219,15 @@ impl SequenceArena {
         if let Some(slot) = self.slots.get_mut(id.slot as usize) {
             if slot.generation == id.generation && slot.record.is_some() {
                 slot.record = None;
-                // Increment generation counter to invalidate any in-flight references (ABA protection)
-                slot.generation = slot.generation.wrapping_add(1).max(1);
-                self.free_slots.push(id.slot);
+                // Advance the generation to invalidate in-flight references (ABA protection).
+                // At u32::MAX the slot is retired instead of wrapping, so no id can ever repeat.
+                if slot.generation == u32::MAX {
+                    slot.retired = true;
+                    self.retired_slots_count += 1;
+                } else {
+                    slot.generation += 1;
+                    self.free_slots.push(id.slot);
+                }
                 self.active_count = self.active_count.saturating_sub(1);
                 return true;
             }
@@ -228,3 +255,47 @@ impl SequenceArena {
         self.slots.iter_mut().filter_map(|s| s.record.as_mut())
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn free_below_max_advances_generation_and_reuses_slot() {
+        let mut arena = SequenceArena::with_start_generation(1, u32::MAX - 1);
+        let id = arena.allocate(1, 1, 0, 0).unwrap();
+        assert_eq!(id.generation, u32::MAX - 1);
+        assert!(arena.free(id));
+        assert_eq!(arena.retired_slots(), 0);
+        let next = arena.allocate(1, 1, 0, 0).unwrap();
+        assert_eq!(next.slot, id.slot);
+        assert_eq!(next.generation, u32::MAX);
+        assert!(!arena.validate(id));
+    }
+
+    #[test]
+    fn free_at_max_retires_slot_and_never_resurrects_stale_id() {
+        let mut arena = SequenceArena::with_start_generation(2, u32::MAX);
+        let id = arena.allocate(1, 1, 0, 0).unwrap();
+        assert_eq!(id.generation, u32::MAX);
+        assert!(arena.free(id));
+        assert_eq!(arena.retired_slots(), 1);
+        assert!(!arena.validate(id));
+        assert!(!arena.free(id));
+
+        // Retired slot is not handed out again; the other slot still works.
+        let other = arena.allocate(1, 1, 0, 0).unwrap();
+        assert_ne!(other.slot, id.slot);
+        assert!(arena.validate(other));
+        assert!(!arena.validate(id));
+    }
+
+    #[test]
+    fn retired_only_slot_exhausts_capacity() {
+        let mut arena = SequenceArena::with_start_generation(1, u32::MAX);
+        let id = arena.allocate(1, 1, 0, 0).unwrap();
+        assert!(arena.free(id));
+        assert!(arena.allocate(1, 1, 0, 0).is_err());
+        assert_eq!(arena.active_count(), 0);
+    }
+}
diff --git a/crates/aien-scheduler/src/sequence.rs b/crates/aien-scheduler/src/sequence.rs
index b7f94814..a1f0d537 100644
--- a/crates/aien-scheduler/src/sequence.rs
+++ b/crates/aien-scheduler/src/sequence.rs
@@ -357,6 +357,16 @@ impl SequenceArena {
         }
     }
 
+    /// Test-only: start every slot at `generation` so the u32::MAX boundary is reachable.
+    #[cfg(test)]
+    pub(crate) fn with_start_generation(capacity: usize, generation: u32) -> Self {
+        let mut arena = Self::with_capacity(capacity);
+        for slot in &mut arena.slots {
+            slot.generation = generation;
+        }
+        arena
+    }
+
     /// Allocates an active sequence slot with a non-zero generation.
     /// Retires slot if generation wraps to u32::MAX.
     pub fn allocate_slot(&mut self) -> Result<SequenceId, String> {
@@ -682,6 +692,46 @@ mod tests {
         assert_eq!(id2.generation, 1);
     }
 
+    fn insert_test_seq(arena: &mut SequenceArena) -> SequenceId {
+        let prompt: PromptHandle = Arc::from(vec![1, 2, 3].into_boxed_slice());
+        arena
+            .insert_with(
+                prompt,
+                ModelHandle(0),
+                KvHandle(0),
+                Priority::Normal,
+                None,
+                None,
+                10,
+                SamplingParams::default(),
+                None,
+            )
+            .unwrap()
+    }
+
+    #[test]
+    fn test_generation_boundary_below_max_reuses_then_retires_at_max() {
+        let mut arena = SequenceArena::with_start_generation(2, u32::MAX - 1);
+        let id = insert_test_seq(&mut arena);
+        assert_eq!(id.generation, u32::MAX - 1);
+        assert!(arena.free_sequence(id));
+        assert_eq!(arena.retired_slots(), 0);
+
+        // Slot is reused at exactly u32::MAX.
+        let top = insert_test_seq(&mut arena);
+        assert_eq!(top.slot, id.slot);
+        assert_eq!(top.generation, u32::MAX);
+        assert!(arena.get(id).is_none());
+
+        // Freeing at u32::MAX retires; neither stale id resolves, none is reallocated.
+        assert!(arena.free_sequence(top));
+        assert_eq!(arena.retired_slots(), 1);
+        assert!(arena.get(top).is_none());
+        assert!(!arena.free_sequence(top));
+        let next = insert_test_seq(&mut arena);
+        assert_ne!(next.slot, top.slot);
+    }
+
     #[test]
     fn test_stale_work_rejection() {
         let mut arena = SequenceArena::new();