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

closed derived 2aacab8598084dac #152

Imported from GitHub aien-dev/aien-sovereign-core-mv#152 (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 1348b49f1c1071bb350bfc60406f0bfecf1291ae · Head f888e700bdcaa3e44fb6c9cfe319367365602b55

Fetch it

A git bundle of the pull request's head, 18969 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/2aacab8598084dac.bundle -o 2aacab8598084dac.bundle
git fetch 2aacab8598084dac.bundle refs/pull/152/head

Raw bundle · 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
152
f888e700bdcaa3e44fb6c9cfe319367365602b55
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":152,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/152","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:07Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs
index 8fc134c6..a8aed47b 100644
--- a/crates/aien-inference-abi/src/lib.rs
+++ b/crates/aien-inference-abi/src/lib.rs
@@ -255,10 +255,13 @@ pub trait AienInferenceBackend: Send + Sync {
         Ok(())
     }
 
-    /// Drops the backend's per-sequence state for `seq_id`. Reclaim wiring
-    /// (calling this when a sequence finishes or a swarm is cancelled) is
-    /// PREFILL-E2E cut C5; it is not called by the runtime yet.
-    /// Default: no-op.
+    /// Drops the backend's per-sequence state for `seq_id` (PREFILL-E2E
+    /// bullet 12). The runtime spine calls it for every finished branch, for
+    /// the swarm root once its last branch finished, and for every sequence of
+    /// a cancelled swarm, always after the runtime freed the KV blocks and
+    /// never while a step is executing. Must not free KV: the runtime owns the
+    /// block tables. Unknown ids are a no-op (a cancelled branch may already
+    /// have finished). Default: no-op.
     fn release_sequence(&mut self, _seq_id: u64) -> Result<(), String> {
         Ok(())
     }
diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs
index af289e1e..355158a1 100644
--- a/crates/aien-inference-abi/src/transformer_backend.rs
+++ b/crates/aien-inference-abi/src/transformer_backend.rs
@@ -1502,6 +1502,20 @@ impl AienInferenceBackend for NativeTransformerBackend {
         Ok(())
     }
 
+    /// PREFILL-E2E C5 (bullet 12): removes this request's entry from the
+    /// per-sequence map (tokens and, unpaged, dense K/V layers) and any pending
+    /// prefill token (C3). The map is the
+    /// backend's only per-request state. Unlike the inherent
+    /// `NativeTransformerBackend::release_sequence` (standalone generation,
+    /// which owns its KV), this never touches the KV manager: in the runtime
+    /// the scheduler and swarm manager free the block tables, and freeing here
+    /// too would race their accounting. Unknown ids are a no-op.
+    fn release_sequence(&mut self, seq_id: u64) -> Result<(), String> {
+        self.sequences.remove(&seq_id);
+        self.pending_prefill_token.remove(&seq_id);
+        Ok(())
+    }
+
     async fn execute_step(
         &mut self,
         batch: &ScheduledBatch,
diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs
index 7ed33bc3..5b0b930e 100644
--- a/crates/aien-runtime/src/spine.rs
+++ b/crates/aien-runtime/src/spine.rs
@@ -31,6 +31,11 @@ pub struct AienRuntimeSpine {
     /// not yet: (parent, child) KV ids, applied via the backend's
     /// `fork_sequence` at the start of the next `step`, before any decode.
     pending_backend_forks: Vec<(u64, u64)>,
+    /// PREFILL-E2E C5: sequence ids whose KV and arena slots were reclaimed
+    /// without a backend in reach (swarm cancel). Their backend per-sequence
+    /// state is released by `release_pending_backend_sequences`, which `step`
+    /// calls first.
+    pending_backend_releases: Vec<u64>,
 }
 
 impl AienRuntimeSpine {
@@ -50,6 +55,7 @@ impl AienRuntimeSpine {
             controller: RuntimeController::new(),
             step_counter: 0,
             pending_backend_forks: Vec::new(),
+            pending_backend_releases: Vec::new(),
         }
     }
 
@@ -146,6 +152,12 @@ impl AienRuntimeSpine {
     ) -> Result<Option<StepMetrics>, String> {
         self.step_counter += 1;
 
+        // PREFILL-E2E C5: backend state of sequences cancelled since the last
+        // step; their KV is already freed. Known gap: CancelSwarm does not
+        // remove the branches from the scheduler's queues (no scheduler
+        // cancel API yet), so the scheduler may still re-admit them.
+        self.release_pending_backend_sequences(backend)?;
+
         // PREFILL-E2E C4: backend state for subagent forks made since the
         // last step, before the scheduler can decode the children.
         for (parent, child) in std::mem::take(&mut self.pending_backend_forks) {
@@ -194,13 +206,27 @@ impl AienRuntimeSpine {
                             record.state = SequenceState::Completed;
                         }
                         self.arena.free(seq_id);
-                        let mut kv = self.kv_manager.write();
-                        self.swarm_manager.note_sequence_finished(
-                            seq_id,
-                            &mut self.arena,
-                            &mut kv,
-                            &mut self.world_store,
-                        );
+                        let reclaimed_root = {
+                            let mut kv = self.kv_manager.write();
+                            self.swarm_manager.note_sequence_finished(
+                                seq_id,
+                                &mut self.arena,
+                                &mut kv,
+                                &mut self.world_store,
+                            )
+                        };
+                        // PREFILL-E2E C5 (bullet 12): drop the backend's
+                        // per-sequence state. Safe order: this runs after
+                        // execute_step returned, so the backend no longer
+                        // reads this sequence's KV (the scheduler already
+                        // freed it), and the KV lock is released first. The
+                        // root goes last, once its final branch finished:
+                        // branches hold their own copy of the root's tokens
+                        // (fork_sequence) and never read the root's state.
+                        backend.release_sequence(*request_id)?;
+                        if let Some(root) = reclaimed_root {
+                            backend.release_sequence(root.as_u64())?;
+                        }
                     }
                 }
             }
@@ -210,6 +236,24 @@ impl AienRuntimeSpine {
         }
     }
 
+    /// PREFILL-E2E C5: releases the backend per-sequence state of every
+    /// sequence reclaimed without a backend in reach (swarm cancel). Runs at
+    /// the start of each `step`; callers that stop stepping after a cancel
+    /// call it directly. Returns the number of ids released.
+    pub fn release_pending_backend_sequences<B: AienInferenceBackend>(
+        &mut self,
+        backend: &mut B,
+    ) -> Result<usize, String> {
+        let ids = std::mem::take(&mut self.pending_backend_releases);
+        // A cancelled sequence must not be forked from or into afterwards.
+        self.pending_backend_forks
+            .retain(|(parent, child)| !ids.contains(parent) && !ids.contains(child));
+        for &id in &ids {
+            backend.release_sequence(id)?;
+        }
+        Ok(ids.len())
+    }
+
     /// Prefills every pending swarm root through the scheduler's completion
     /// fence and, once the root is PrefillReady, shares its blocks with the
     /// branches. Returns the number of root prompt tokens prefilled.
@@ -333,7 +377,10 @@ impl AienRuntimeSpine {
                     &mut kv,
                     &mut self.world_store,
                 ) {
-                    Ok(()) => {
+                    Ok(released) => {
+                        // KV, arena slots and branch worlds are reclaimed;
+                        // backend state follows on the next step (C5).
+                        self.pending_backend_releases.extend(released);
                         self.controller
                             .mark_operation_processed(envelope.operation_id);
                         ControlResponse::SwarmCancelled { swarm_id }
diff --git a/crates/aien-runtime/src/swarm.rs b/crates/aien-runtime/src/swarm.rs
index cdd88fcf..687a4f9a 100644
--- a/crates/aien-runtime/src/swarm.rs
+++ b/crates/aien-runtime/src/swarm.rs
@@ -215,13 +215,16 @@ impl SwarmManager {
 
     /// Cancels a swarm and reclaims its resources: KV sequences, arena slots,
     /// and branch worlds. The root world is retained; branch worlds are dropped.
+    /// Returns the sequence ids (root first, then every branch) whose backend
+    /// per-sequence state the caller must release (PREFILL-E2E C5); the
+    /// swarm manager has no backend handle.
     pub fn cancel_swarm(
         &mut self,
         swarm_id: u64,
         arena: &mut SequenceArena,
         kv: &mut AienKvManager,
         worlds: &mut WorldStore,
-    ) -> Result<(), String> {
+    ) -> Result<Vec<u64>, String> {
         let swarm = self
             .swarms
             .get_mut(&swarm_id)
@@ -256,29 +259,32 @@ impl SwarmManager {
         worlds.collect_garbage();
 
         swarm.state = SwarmState::Completed;
-        Ok(())
+        let mut released = Vec::with_capacity(swarm.branch_sequences.len() + 1);
+        released.push(swarm.root_sequence_id.as_u64());
+        released.extend(swarm.branch_sequences.iter().map(|b| b.as_u64()));
+        Ok(released)
     }
 
     /// Records a branch that finished naturally. Once every branch of a
     /// running swarm has finished, reclaims the whole swarm: root arena slot,
     /// root KV blocks, and all branch worlds. Without this, the root sequence
     /// pins the arena forever and finished branch worlds leak.
+    /// Returns the root sequence id when this call reclaimed the swarm, so the
+    /// caller can release the root's backend state (PREFILL-E2E C5).
     pub fn note_sequence_finished(
         &mut self,
         seq_id: SequenceId,
         arena: &mut SequenceArena,
         kv: &mut AienKvManager,
         worlds: &mut WorldStore,
-    ) {
+    ) -> Option<SequenceId> {
         let swarm_id = self.swarms.iter().find_map(|(id, swarm)| {
             (swarm.state == SwarmState::Running
                 && swarm.branch_sequences.contains(&seq_id)
                 && !swarm.finished_branches.contains(&seq_id))
             .then_some(*id)
         });
-        let Some(swarm_id) = swarm_id else {
-            return;
-        };
+        let swarm_id = swarm_id?;
 
         let swarm = self
             .swarms
@@ -286,7 +292,7 @@ impl SwarmManager {
             .expect("swarm id from live iterator must exist");
         swarm.finished_branches.push(seq_id);
         if swarm.finished_branches.len() < swarm.branch_sequences.len() {
-            return;
+            return None;
         }
 
         if let Some(root_rec) = arena.get_mut(swarm.root_sequence_id) {
@@ -301,6 +307,7 @@ impl SwarmManager {
         }
         worlds.collect_garbage();
         swarm.state = SwarmState::Completed;
+        Some(swarm.root_sequence_id)
     }
 
     pub fn active_swarm_count(&self) -> usize {
diff --git a/crates/aien-runtime/tests/swarm_reclaim_test.rs b/crates/aien-runtime/tests/swarm_reclaim_test.rs
new file mode 100644
index 00000000..0c7731a5
--- /dev/null
+++ b/crates/aien-runtime/tests/swarm_reclaim_test.rs
@@ -0,0 +1,256 @@
+//! PREFILL-E2E-0 cut C5: all sequences, worlds and KV reclaimed (bullet 12).
+//!
+//! Drives the real NativeTransformerBackend (reference weights, CPU) through
+//! spine + scheduler + one pooled KV shared by both
+//! (`aien_runtime::shared_kv::build_shared_kv_runtime`):
+//! - natural completion: one root + 4 branches run to completion; afterwards
+//!   the backend holds no per-sequence state, the shared KV has no allocated
+//!   block, the spine arena has no active sequence and every branch world is
+//!   gone (only the root world remains);
+//! - cancel midway: the same swarm is cancelled after its first decode step;
+//!   the same end state must hold once the spine released the cancelled
+//!   sequences' backend state.
+//!
+//! Mutant (outside the repo, ~/workspace/hive/PE2E-C5/mutant.patch): the
+//! spine no longer calls `release_sequence` (finish path and cancel drain).
+//! Then the backend keeps the root and branch entries and both tests fail
+//! on the backend release check with the message `RECLAIM_BACKEND_LEAK`
+//! (the forge greps the mutant output for it, once per test).
+//!
+//! State isolation: `AienRuntimeSpine::new` builds a `RuntimeController`
+//! (spine.rs:55) that loads and persists processed operation ids at
+//! `$AIEN_RUNTIME_STATE_DIR/processed_operations.json`, falling back to the
+//! shared `/tmp/aien-runtime-processed-ops.json` (control.rs:102-108,
+//! 119-127, 134-144). The cancel test sends a fixed operation id, so every
+//! run gets its own fresh state directory (as swarm_completion_test.rs:12-14
+//! does), else a rerun is refused with "Operation N already processed".
+//!
+//! Known gap, not covered here: `CancelSwarm` does not remove the cancelled
+//! branches from the scheduler's queues (no scheduler cancel API exists), so
+//! the cancel test does not step the spine again after the cancel.
+
+use std::path::PathBuf;
+use std::sync::{Arc, OnceLock};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use aien_inference_abi::{
+    ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, TransformerWeights,
+};
+use aien_runtime::control::{ControlCommand, ControlEnvelope, ControlResponse};
+use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing};
+use aien_runtime::spine::AienRuntimeSpine;
+use aien_runtime::swarm::{SwarmConfig, SwarmRecord};
+use aien_scheduler::SchedulerConfig;
+
+const BRANCHES: usize = 4;
+const PROMPT: [u32; 6] = [5, 17, 42, 3, 88, 61];
+
+fn c5_config() -> ModelConfig {
+    ModelConfig {
+        model_id: "pe2e-c5-reclaim-reference".to_string(),
+        max_sequence_length: 256,
+        // 6-token prompt over 4-token blocks: the shared tail block is
+        // partial, so each branch's first decode copies it (COW) and owns a
+        // private block that must be reclaimed too.
+        block_size: 4,
+        num_layers: 3,
+        num_heads: 4,
+        head_dim: 8,
+        num_kv_heads: 2,
+        hidden_dim: 32,
+        intermediate_dim: 64,
+        vocab_size: 97,
+        rms_norm_eps: 1e-5,
+        rope_theta: 10000.0,
+    }
+}
+
+fn c5_scheduler() -> SchedulerConfig {
+    SchedulerConfig {
+        max_batch_size: 32,
+        max_batch_tokens: 2048,
+        max_prefill_tokens: 1024,
+        prefill_chunk_size: 128,
+        chunk_prefill: true,
+        watermark_blocks: 2,
+    }
+}
+
+fn c5_swarm(max_tokens: usize) -> SwarmConfig {
+    SwarmConfig {
+        model_handle: 1,
+        branch_count: BRANCHES,
+        max_active_sequences: BRANCHES,
+        max_tokens_per_branch: max_tokens,
+        root_world_id: 0,
+        priority: 1,
+    }
+}
+
+/// One fresh, empty controller state directory per test process (pid +
+/// nanosecond clock, so neither a rerun nor a reused pid sees old ids). Set
+/// once: both tests run as threads of one process and the env var is
+/// process-wide, so per-test values would race.
+fn fresh_state_dir() -> &'static PathBuf {
+    static DIR: OnceLock<PathBuf> = OnceLock::new();
+    DIR.get_or_init(|| {
+        let nanos = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .expect("clock after epoch")
+            .as_nanos();
+        let dir = std::env::temp_dir().join(format!(
+            "aien-swarm-reclaim-test-{}-{}",
+            std::process::id(),
+            nanos
+        ));
+        let _ = std::fs::remove_dir_all(&dir);
+        std::fs::create_dir_all(&dir).expect("create fresh state dir");
+        std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir);
+        dir
+    })
+}
+
+fn build() -> (AienRuntimeSpine, NativeTransformerBackend) {
+    // Before the spine (and its RuntimeController) is built.
+    fresh_state_dir();
+    let weights = TransformerWeights::reference_test_weights(&c5_config());
+    build_shared_kv_runtime(
+        weights,
+        Arc::new(ReferenceCpuBackend::new()),
+        c5_scheduler(),
+        SharedKvSizing {
+            arena_capacity: 64,
+            total_blocks: 64,
+        },
+    )
+    .expect("build shared KV runtime")
+}
+
+fn launch(spine: &mut AienRuntimeSpine, max_tokens: usize) -> SwarmRecord {
+    let swarm_id = spine
+        .launch_swarm(c5_swarm(max_tokens), &PROMPT)
+        .expect("launch swarm");
+    spine.swarm_manager.get_swarm(swarm_id).unwrap().clone()
+}
+
+/// Bullet 12 end state, shared by both tests.
+fn assert_fully_reclaimed(
+    spine: &AienRuntimeSpine,
+    backend: &NativeTransformerBackend,
+    swarm: &SwarmRecord,
+    worlds_before_launch: usize,
+) {
+    let leaked: Vec<u64> = backend.sequences.keys().copied().collect();
+    assert!(
+        leaked.is_empty(),
+        "RECLAIM_VIOLATION: RECLAIM_BACKEND_LEAK backend still holds per-sequence state for {:?} (root {}, branches {:?})",
+        leaked,
+        swarm.root_sequence_id.as_u64(),
+        swarm
+            .branch_sequences
+            .iter()
+            .map(|b| b.as_u64())
+            .collect::<Vec<_>>()
+    );
+    let kv = spine.kv_manager.read();
+    assert_eq!(
+        kv.allocated_block_count(),
+        0,
+        "RECLAIM_VIOLATION: shared KV still has allocated blocks"
+    );
+    assert!(kv
+        .get_block_table(swarm.root_sequence_id.as_u64())
+        .is_none());
+    for b in &swarm.branch_sequences {
+        assert!(kv.get_block_table(b.as_u64()).is_none());
+    }
+    drop(kv);
+    assert_eq!(
+        spine.arena.active_count(),
+        0,
+        "RECLAIM_VIOLATION: spine arena still has active sequences"
+    );
+    for &w in &swarm.branch_worlds {
+        assert!(
+            spine.world_store.get_world(w).is_none(),
+            "RECLAIM_VIOLATION: branch world {} still alive",
+            w
+        );
+    }
+    assert_eq!(
+        spine.world_store.active_world_count(),
+        worlds_before_launch + 1,
+        "only the root world may remain"
+    );
+    assert_eq!(spine.swarm_manager.active_swarm_count(), 0);
+}
+
+#[tokio::test]
+async fn swarm_completion_reclaims_backend_kv_arena_and_worlds() {
+    let (mut spine, mut backend) = build();
+    let worlds_before = spine.world_store.active_world_count();
+    let swarm = launch(&mut spine, 3);
+    assert_eq!(swarm.branch_sequences.len(), BRANCHES);
+
+    let mut steps = 0;
+    let mut peak_backend_sequences = 0usize;
+    while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) && steps < 50
+    {
+        steps += 1;
+        spine.step(&mut backend).await.expect("spine step");
+        peak_backend_sequences = peak_backend_sequences.max(backend.sequences.len());
+    }
+    assert_eq!(
+        spine.scheduler.metrics().finished_requests as usize,
+        BRANCHES,
+        "every branch must finish"
+    );
+    // Counterexample guard: the run really created backend state for the
+    // root and every branch, so an empty map at the end means reclaim.
+    assert_eq!(
+        peak_backend_sequences,
+        BRANCHES + 1,
+        "root + every branch must have held backend state during the run"
+    );
+
+    assert_fully_reclaimed(&spine, &backend, &swarm, worlds_before);
+}
+
+#[tokio::test]
+async fn swarm_cancel_midway_reclaims_backend_kv_arena_and_worlds() {
+    let (mut spine, mut backend) = build();
+    let worlds_before = spine.world_store.active_world_count();
+    // Long enough that no branch finishes before the cancel.
+    let swarm = launch(&mut spine, 16);
+
+    // Step 1: root prefill + fence + backend forks. Step 2: first decode.
+    spine.step(&mut backend).await.expect("prefill step");
+    spine.step(&mut backend).await.expect("first decode step");
+    assert_eq!(spine.scheduler.metrics().finished_requests, 0);
+    assert_eq!(
+        backend.sequences.len(),
+        BRANCHES + 1,
+        "root + every branch must hold backend state before the cancel"
+    );
+    assert!(spine.kv_manager.read().allocated_block_count() > 0);
+
+    let resp = spine.handle_control_command(ControlEnvelope {
+        protocol_version: 1,
+        request_id: 1,
+        operation_id: 0xC5,
+        operator_session: 1,
+        command: ControlCommand::CancelSwarm(swarm.id),
+    });
+    assert!(
+        matches!(resp, ControlResponse::SwarmCancelled { swarm_id } if swarm_id == swarm.id),
+        "cancel must succeed: {:?}",
+        resp
+    );
+
+    let released = spine
+        .release_pending_backend_sequences(&mut backend)
+        .expect("release cancelled backend state");
+    assert_eq!(released, BRANCHES + 1, "root + every branch released");
+
+    assert_fully_reclaimed(&spine, &backend, &swarm, worlds_before);
+}