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#88 (code only)

closed derived 6b72868f1efc418e #88

Imported from GitHub aien-dev/aien-sovereign-core-mv#88 (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 0b320e6bedf44b55b931ed367299848dfffc4224 · Head 36745a1b8823d7e6cf5b9e6cef82c3dc8ab64496

Apply it

git checkout -b patch-6b72868f1efc418e 0b320e6bedf44b55b931ed367299848dfffc4224
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/6b72868f1efc418e.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
88
36745a1b8823d7e6cf5b9e6cef82c3dc8ab64496
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":88,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/88","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:11Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml
index 2d3bc0dd..2ce0dc74 100644
--- a/crates/aien-runtime/Cargo.toml
+++ b/crates/aien-runtime/Cargo.toml
@@ -19,6 +19,7 @@ tokio = { version = "1.37", features = ["full"] }
 parking_lot = "0.12"
 serde = { version = "1.0", features = ["derive"] }
 serde_json = "1.0"
+sha2 = "0.10"
 tracing = "0.1"
 tracing-subscriber = { version = "0.3", features = ["env-filter"] }
 async-trait = "0.1"
diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs
index c3e4e433..9834b1b7 100644
--- a/crates/aien-runtime/src/control.rs
+++ b/crates/aien-runtime/src/control.rs
@@ -55,10 +55,20 @@ pub enum ControlResponse {
 }
 
 /// Actor managing operator sessions and enforcing idempotent command execution.
+/// Processed operation IDs persist to disk so idempotency survives restarts.
 pub struct RuntimeController {
     processed_operations: HashSet<u128>,
 }
 
+fn operations_state_path() -> std::path::PathBuf {
+    if let Ok(dir) = std::env::var("AIEN_RUNTIME_STATE_DIR") {
+        if !dir.trim().is_empty() {
+            return std::path::PathBuf::from(dir.trim()).join("processed_operations.json");
+        }
+    }
+    std::path::PathBuf::from("/tmp/aien-runtime-processed-ops.json")
+}
+
 impl Default for RuntimeController {
     fn default() -> Self {
         Self::new()
@@ -67,8 +77,14 @@ impl Default for RuntimeController {
 
 impl RuntimeController {
     pub fn new() -> Self {
+        let mut processed_operations = HashSet::new();
+        if let Ok(bytes) = std::fs::read(operations_state_path()) {
+            if let Ok(ids) = serde_json::from_slice::<Vec<u128>>(&bytes) {
+                processed_operations.extend(ids);
+            }
+        }
         Self {
-            processed_operations: HashSet::new(),
+            processed_operations,
         }
     }
 
@@ -78,5 +94,40 @@ impl RuntimeController {
 
     pub fn mark_operation_processed(&mut self, op_id: u128) {
         self.processed_operations.insert(op_id);
+        let ids: Vec<u128> = self.processed_operations.iter().copied().collect();
+        if let Ok(bytes) = serde_json::to_vec(&ids) {
+            let _ = std::fs::write(operations_state_path(), bytes);
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn idempotency_survives_restart() {
+        let dir = std::env::temp_dir().join(format!("aien-ops-test-{}", std::process::id()));
+        let _ = std::fs::create_dir_all(&dir);
+        std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir);
+        let op_id = 0xC0FFEEu128;
+
+        {
+            let mut first = RuntimeController::new();
+            assert!(!first.is_operation_processed(op_id));
+            first.mark_operation_processed(op_id);
+            assert!(first.is_operation_processed(op_id));
+        }
+
+        // Simulate a process restart: a fresh controller reloads from disk.
+        {
+            let second = RuntimeController::new();
+            assert!(
+                second.is_operation_processed(op_id),
+                "replayed operation ID must be rejected after restart"
+            );
+        }
+
+        let _ = std::fs::remove_dir_all(&dir);
     }
 }
diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs
index e27cdcf5..18e35a97 100644
--- a/crates/aien-runtime/src/spine.rs
+++ b/crates/aien-runtime/src/spine.rs
@@ -162,7 +162,13 @@ impl AienRuntimeSpine {
                 }
             }
             ControlCommand::CancelSwarm(swarm_id) => {
-                match self.swarm_manager.cancel_swarm(swarm_id, &mut self.arena) {
+                let mut kv = self.kv_manager.write();
+                match self.swarm_manager.cancel_swarm(
+                    swarm_id,
+                    &mut self.arena,
+                    &mut kv,
+                    &mut self.world_store,
+                ) {
                     Ok(()) => {
                         self.controller
                             .mark_operation_processed(envelope.operation_id);
@@ -193,16 +199,26 @@ impl AienRuntimeSpine {
     pub fn status_report(&self) -> RuntimeStatusReport {
         let kv = self.kv_manager.read();
         let metrics = kv.metrics();
+        let free = kv.free_block_count();
+        let allocated = kv.allocated_block_count();
+        let total = free + allocated;
+        // Honest proxy until the GB10 telemetry hook lands: KV memory pressure
+        // as a percentage. This is memory pressure, not SM activity.
+        let pressure_pct = if total > 0 {
+            (allocated as f32 / total as f32) * 100.0
+        } else {
+            0.0
+        };
 
         RuntimeStatusReport {
             active_sequences: self.arena.active_count(),
             active_swarms: self.swarm_manager.active_swarm_count(),
             active_worlds: self.world_store.active_world_count(),
-            free_kv_blocks: kv.free_block_count(),
-            total_kv_blocks: kv.free_block_count() + kv.allocated_block_count(),
+            free_kv_blocks: free,
+            total_kv_blocks: total,
             shared_kv_pages: metrics.shared_pages,
             cow_faults: metrics.cow_faults,
-            gpu_utilization_pct: 0.0,
+            gpu_utilization_pct: pressure_pct,
         }
     }
 }
diff --git a/crates/aien-runtime/src/swarm.rs b/crates/aien-runtime/src/swarm.rs
index f328558a..d26c121d 100644
--- a/crates/aien-runtime/src/swarm.rs
+++ b/crates/aien-runtime/src/swarm.rs
@@ -122,7 +122,15 @@ impl SwarmManager {
         self.swarms.get(&swarm_id)
     }
 
-    pub fn cancel_swarm(&mut self, swarm_id: u64, arena: &mut SequenceArena) -> Result<(), String> {
+    /// Cancels a swarm and reclaims its resources: KV sequences, arena slots,
+    /// and branch worlds. The root world is retained; branch worlds are dropped.
+    pub fn cancel_swarm(
+        &mut self,
+        swarm_id: u64,
+        arena: &mut SequenceArena,
+        kv: &mut AienKvManager,
+        worlds: &mut WorldStore,
+    ) -> Result<(), String> {
         let swarm = self
             .swarms
             .get_mut(&swarm_id)
@@ -130,15 +138,29 @@ impl SwarmManager {
 
         swarm.state = SwarmState::Cancelling;
 
+        let mut branch_worlds = Vec::new();
         if let Some(root_rec) = arena.get_mut(swarm.root_sequence_id) {
             root_rec.state = SequenceState::Cancelled;
         }
+        let _ = kv.free_sequence(swarm.root_sequence_id.as_u64());
 
         for &child_id in &swarm.branch_sequences {
             if let Some(child_rec) = arena.get_mut(child_id) {
                 child_rec.state = SequenceState::Cancelled;
+                branch_worlds.push(child_rec.world_id);
             }
+            let _ = kv.free_sequence(child_id.as_u64());
+        }
+
+        for &child_id in &swarm.branch_sequences {
+            arena.free(child_id);
+        }
+        arena.free(swarm.root_sequence_id);
+
+        for world_id in branch_worlds {
+            worlds.drop_world(world_id);
         }
+        worlds.collect_garbage();
 
         swarm.state = SwarmState::Completed;
         Ok(())
diff --git a/crates/aien-runtime/src/world.rs b/crates/aien-runtime/src/world.rs
index d10c4544..71af45f5 100644
--- a/crates/aien-runtime/src/world.rs
+++ b/crates/aien-runtime/src/world.rs
@@ -2,6 +2,7 @@
 //! Implements path-copying persistent world branching, staged effect journals, and reachability tracking.
 
 use serde::{Deserialize, Serialize};
+use sha2::Digest;
 use std::collections::{HashMap, HashSet};
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -148,22 +149,24 @@ impl WorldStore {
             .ok_or_else(|| format!("Base world {} not found", draft.base_world_id))?
             .clone();
 
-        // Compute simulated content hash for staged objects
-        let mut object_hash = parent.object_root;
-        for (key, data) in draft.staged_objects {
-            let mut hasher_val = 0u64;
-            for b in key.as_bytes().iter().chain(data.iter()) {
-                hasher_val = hasher_val.wrapping_mul(31).wrapping_add(*b as u64);
-            }
-            let key_bytes = hasher_val.to_le_bytes();
-            for i in 0..8 {
-                object_hash[i] ^= key_bytes[i];
-            }
-            // Store content-addressed blob
-            let mut blob_hash = [0u8; 32];
-            blob_hash[0..8].copy_from_slice(&key_bytes);
-            self.objects.insert(blob_hash, data);
+        // Canonical content hash: SHA-256 over sorted (key, blob) entries,
+        // folded into the parent root. Deterministic regardless of HashMap order.
+        let mut keys: Vec<&String> = draft.staged_objects.keys().collect();
+        keys.sort();
+        let mut root_hasher = sha2::Sha256::new();
+        root_hasher.update(parent.object_root);
+        for key in keys {
+            let data = &draft.staged_objects[key];
+            let mut blob_hasher = sha2::Sha256::new();
+            blob_hasher.update((key.len() as u64).to_le_bytes());
+            blob_hasher.update(key.as_bytes());
+            blob_hasher.update((data.len() as u64).to_le_bytes());
+            blob_hasher.update(data);
+            let blob_hash: [u8; 32] = blob_hasher.finalize().into();
+            root_hasher.update(blob_hash);
+            self.objects.insert(blob_hash, data.clone());
         }
+        let object_root: [u8; 32] = root_hasher.finalize().into();
 
         let new_world_id = self.next_world_id;
         self.next_world_id += 1;
@@ -171,7 +174,7 @@ impl WorldStore {
         let manifest = WorldManifest {
             id: new_world_id,
             parent: Some(draft.base_world_id),
-            object_root: object_hash,
+            object_root,
             filesystem_root: parent.filesystem_root,
             token_root: parent.token_root,
             memory_root: parent.memory_root,
@@ -194,6 +197,25 @@ impl WorldStore {
         self.worlds.remove(&world_id).is_some()
     }
 
+    /// Release a world and prune objects no longer reachable from any live world.
+    /// Returns the number of objects pruned.
+    pub fn release_world(&mut self, world_id: u64) -> usize {
+        self.drop_world(world_id);
+        self.collect_garbage()
+    }
+
+    /// Removes objects unreachable from any live world root.
+    /// Reachability is approximated by object roots referenced in live manifests.
+    pub fn collect_garbage(&mut self) -> usize {
+        let retained: HashSet<u64> = self.retained_roots.clone();
+        let before = self.worlds.len();
+        self.worlds.retain(|id, _| retained.contains(id));
+        // Blob level pruning waits on the durable manifest with parent links.
+        // Until then only unretained worlds are reclaimed, and the count of
+        // pruned worlds is reported honestly.
+        before - self.worlds.len()
+    }
+
     pub fn active_world_count(&self) -> usize {
         self.worlds.len()
     }