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
aien-sovereign-core-mv / crates / aien-runtime / tests / swarm_reclaim_test.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! PREFILL-E2E-0 cut C5: all sequences, worlds and KV reclaimed (bullet 12). |
| 17 | //! |
| 18 | //! Drives the real NativeTransformerBackend (reference weights, CPU) through |
| 19 | //! spine + scheduler + one pooled KV shared by both |
| 20 | //! (`aien_runtime::shared_kv::build_shared_kv_runtime`): |
| 21 | //! - natural completion: one root + 4 branches run to completion; afterwards |
| 22 | //! the backend holds no per-sequence state, the shared KV has no allocated |
| 23 | //! block, the spine arena has no active sequence and every branch world is |
| 24 | //! gone (only the root world remains); |
| 25 | //! - cancel midway: the same swarm is cancelled after its first decode step; |
| 26 | //! the same end state must hold once the spine released the cancelled |
| 27 | //! sequences' backend state. |
| 28 | //! |
| 29 | //! Mutant (outside the repo, ~/workspace/hive/PE2E-C5/mutant.patch): the |
| 30 | //! spine no longer calls `release_sequence` (finish path and cancel drain). |
| 31 | //! Then the backend keeps the root and branch entries and both tests fail |
| 32 | //! on the backend release check with the message `RECLAIM_BACKEND_LEAK` |
| 33 | //! (the forge greps the mutant output for it, once per test). |
| 34 | //! |
| 35 | //! State isolation: `AienRuntimeSpine::new` builds a `RuntimeController` |
| 36 | //! (spine.rs:55) that loads and persists processed operation ids at |
| 37 | //! `$AIEN_RUNTIME_STATE_DIR/processed_operations.json`, falling back to the |
| 38 | //! shared `/tmp/aien-runtime-processed-ops.json` (control.rs:102-108, |
| 39 | //! 119-127, 134-144). The cancel test sends a fixed operation id, so every |
| 40 | //! run gets its own fresh state directory (as swarm_completion_test.rs:12-14 |
| 41 | //! does), else a rerun is refused with "Operation N already processed". |
| 42 | //! |
| 43 | //! Known gap, not covered here: `CancelSwarm` does not remove the cancelled |
| 44 | //! branches from the scheduler's queues (no scheduler cancel API exists), so |
| 45 | //! the cancel test does not step the spine again after the cancel. |
| 46 | |
| 47 | use std::path::PathBuf; |
| 48 | use std::sync::{Arc, OnceLock}; |
| 49 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 50 | |
| 51 | use aien_inference_abi::{ |
| 52 | ModelConfig, NativeTransformerBackend, ReferenceCpuBackend, TransformerWeights, |
| 53 | }; |
| 54 | use aien_runtime::control::{ControlCommand, ControlEnvelope, ControlResponse}; |
| 55 | use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; |
| 56 | use aien_runtime::spine::AienRuntimeSpine; |
| 57 | use aien_runtime::swarm::{SwarmConfig, SwarmRecord}; |
| 58 | use aien_scheduler::SchedulerConfig; |
| 59 | |
| 60 | const BRANCHES: usize = 4; |
| 61 | const PROMPT: [u32; 6] = [5, 17, 42, 3, 88, 61]; |
| 62 | |
| 63 | fn c5_config() -> ModelConfig { |
| 64 | ModelConfig { |
| 65 | model_id: "pe2e-c5-reclaim-reference".to_string(), |
| 66 | max_sequence_length: 256, |
| 67 | // 6-token prompt over 4-token blocks: the shared tail block is |
| 68 | // partial, so each branch's first decode copies it (COW) and owns a |
| 69 | // private block that must be reclaimed too. |
| 70 | block_size: 4, |
| 71 | num_layers: 3, |
| 72 | num_heads: 4, |
| 73 | head_dim: 8, |
| 74 | num_kv_heads: 2, |
| 75 | hidden_dim: 32, |
| 76 | intermediate_dim: 64, |
| 77 | vocab_size: 97, |
| 78 | rms_norm_eps: 1e-5, |
| 79 | rope_theta: 10000.0, |
| 80 | rope_scaling: None, |
| 81 | tie_word_embeddings: false, |
| 82 | eos_token_ids: Vec::new(), |
| 83 | qk_norm: false, |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | fn c5_scheduler() -> SchedulerConfig { |
| 88 | SchedulerConfig { |
| 89 | max_batch_size: 32, |
| 90 | max_batch_tokens: 2048, |
| 91 | max_prefill_tokens: 1024, |
| 92 | prefill_chunk_size: 128, |
| 93 | chunk_prefill: true, |
| 94 | watermark_blocks: 2, |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | fn c5_swarm(max_tokens: usize) -> SwarmConfig { |
| 99 | SwarmConfig { |
| 100 | model_handle: 1, |
| 101 | branch_count: BRANCHES, |
| 102 | max_active_sequences: BRANCHES, |
| 103 | max_tokens_per_branch: max_tokens, |
| 104 | root_world_id: 0, |
| 105 | priority: 1, |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// One fresh, empty controller state directory per test process (pid + |
| 110 | /// nanosecond clock, so neither a rerun nor a reused pid sees old ids). Set |
| 111 | /// once: both tests run as threads of one process and the env var is |
| 112 | /// process-wide, so per-test values would race. |
| 113 | fn fresh_state_dir() -> &'static PathBuf { |
| 114 | static DIR: OnceLock<PathBuf> = OnceLock::new(); |
| 115 | DIR.get_or_init(|| { |
| 116 | let nanos = SystemTime::now() |
| 117 | .duration_since(UNIX_EPOCH) |
| 118 | .expect("clock after epoch") |
| 119 | .as_nanos(); |
| 120 | let dir = std::env::temp_dir().join(format!( |
| 121 | "aien-swarm-reclaim-test-{}-{}", |
| 122 | std::process::id(), |
| 123 | nanos |
| 124 | )); |
| 125 | let _ = std::fs::remove_dir_all(&dir); |
| 126 | std::fs::create_dir_all(&dir).expect("create fresh state dir"); |
| 127 | std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir); |
| 128 | dir |
| 129 | }) |
| 130 | } |
| 131 | |
| 132 | fn build() -> (AienRuntimeSpine, NativeTransformerBackend) { |
| 133 | // Before the spine (and its RuntimeController) is built. |
| 134 | fresh_state_dir(); |
| 135 | let weights = TransformerWeights::reference_test_weights(&c5_config()); |
| 136 | build_shared_kv_runtime( |
| 137 | weights, |
| 138 | Arc::new(ReferenceCpuBackend::new()), |
| 139 | c5_scheduler(), |
| 140 | SharedKvSizing { |
| 141 | arena_capacity: 64, |
| 142 | total_blocks: 64, |
| 143 | }, |
| 144 | ) |
| 145 | .expect("build shared KV runtime") |
| 146 | } |
| 147 | |
| 148 | fn launch(spine: &mut AienRuntimeSpine, max_tokens: usize) -> SwarmRecord { |
| 149 | let swarm_id = spine |
| 150 | .launch_swarm(c5_swarm(max_tokens), &PROMPT) |
| 151 | .expect("launch swarm"); |
| 152 | spine.swarm_manager.get_swarm(swarm_id).unwrap().clone() |
| 153 | } |
| 154 | |
| 155 | /// Bullet 12 end state, shared by both tests. |
| 156 | fn assert_fully_reclaimed( |
| 157 | spine: &AienRuntimeSpine, |
| 158 | backend: &NativeTransformerBackend, |
| 159 | swarm: &SwarmRecord, |
| 160 | worlds_before_launch: usize, |
| 161 | ) { |
| 162 | let leaked: Vec<u64> = backend.sequences.keys().copied().collect(); |
| 163 | assert!( |
| 164 | leaked.is_empty(), |
| 165 | "RECLAIM_VIOLATION: RECLAIM_BACKEND_LEAK backend still holds per-sequence state for {:?} (root {}, branches {:?})", |
| 166 | leaked, |
| 167 | swarm.root_sequence_id.as_u64(), |
| 168 | swarm |
| 169 | .branch_sequences |
| 170 | .iter() |
| 171 | .map(|b| b.as_u64()) |
| 172 | .collect::<Vec<_>>() |
| 173 | ); |
| 174 | // C6 x C5: the sampling map entry is dropped with the sequence. |
| 175 | assert!( |
| 176 | backend.sampling_params(swarm.root_sequence_id.as_u64()).is_none() |
| 177 | && swarm |
| 178 | .branch_sequences |
| 179 | .iter() |
| 180 | .all(|b| backend.sampling_params(b.as_u64()).is_none()), |
| 181 | "RECLAIM_VIOLATION: RECLAIM_SAMPLING_LEAK backend still holds sampling params for a released sequence" |
| 182 | ); |
| 183 | let kv = spine.kv_manager.read(); |
| 184 | assert_eq!( |
| 185 | kv.allocated_block_count(), |
| 186 | 0, |
| 187 | "RECLAIM_VIOLATION: shared KV still has allocated blocks" |
| 188 | ); |
| 189 | assert!(kv |
| 190 | .get_block_table(swarm.root_sequence_id.as_u64()) |
| 191 | .is_none()); |
| 192 | for b in &swarm.branch_sequences { |
| 193 | assert!(kv.get_block_table(b.as_u64()).is_none()); |
| 194 | } |
| 195 | drop(kv); |
| 196 | assert_eq!( |
| 197 | spine.arena.active_count(), |
| 198 | 0, |
| 199 | "RECLAIM_VIOLATION: spine arena still has active sequences" |
| 200 | ); |
| 201 | for &w in &swarm.branch_worlds { |
| 202 | assert!( |
| 203 | spine.world_store.get_world(w).is_none(), |
| 204 | "RECLAIM_VIOLATION: branch world {} still alive", |
| 205 | w |
| 206 | ); |
| 207 | } |
| 208 | assert_eq!( |
| 209 | spine.world_store.active_world_count(), |
| 210 | worlds_before_launch + 1, |
| 211 | "only the root world may remain" |
| 212 | ); |
| 213 | assert_eq!(spine.swarm_manager.active_swarm_count(), 0); |
| 214 | } |
| 215 | |
| 216 | #[tokio::test] |
| 217 | async fn swarm_completion_reclaims_backend_kv_arena_and_worlds() { |
| 218 | let (mut spine, mut backend) = build(); |
| 219 | let worlds_before = spine.world_store.active_world_count(); |
| 220 | let swarm = launch(&mut spine, 3); |
| 221 | assert_eq!(swarm.branch_sequences.len(), BRANCHES); |
| 222 | |
| 223 | let mut steps = 0; |
| 224 | let mut peak_backend_sequences = 0usize; |
| 225 | while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) && steps < 50 |
| 226 | { |
| 227 | steps += 1; |
| 228 | spine.step(&mut backend).await.expect("spine step"); |
| 229 | peak_backend_sequences = peak_backend_sequences.max(backend.sequences.len()); |
| 230 | } |
| 231 | assert_eq!( |
| 232 | spine.scheduler.metrics().finished_requests as usize, |
| 233 | BRANCHES, |
| 234 | "every branch must finish" |
| 235 | ); |
| 236 | // Counterexample guard: the run really created backend state for the |
| 237 | // root and every branch, so an empty map at the end means reclaim. |
| 238 | assert_eq!( |
| 239 | peak_backend_sequences, |
| 240 | BRANCHES + 1, |
| 241 | "root + every branch must have held backend state during the run" |
| 242 | ); |
| 243 | |
| 244 | assert_fully_reclaimed(&spine, &backend, &swarm, worlds_before); |
| 245 | } |
| 246 | |
| 247 | #[tokio::test] |
| 248 | async fn swarm_cancel_midway_reclaims_backend_kv_arena_and_worlds() { |
| 249 | let (mut spine, mut backend) = build(); |
| 250 | let worlds_before = spine.world_store.active_world_count(); |
| 251 | // Long enough that no branch finishes before the cancel. |
| 252 | let swarm = launch(&mut spine, 16); |
| 253 | |
| 254 | // Step 1: root prefill + fence + backend forks. Step 2: first decode. |
| 255 | spine.step(&mut backend).await.expect("prefill step"); |
| 256 | spine.step(&mut backend).await.expect("first decode step"); |
| 257 | assert_eq!(spine.scheduler.metrics().finished_requests, 0); |
| 258 | assert_eq!( |
| 259 | backend.sequences.len(), |
| 260 | BRANCHES + 1, |
| 261 | "root + every branch must hold backend state before the cancel" |
| 262 | ); |
| 263 | assert!(spine.kv_manager.read().allocated_block_count() > 0); |
| 264 | |
| 265 | let resp = spine.handle_control_command(ControlEnvelope { |
| 266 | protocol_version: 1, |
| 267 | request_id: 1, |
| 268 | operation_id: 0xC5, |
| 269 | operator_session: 1, |
| 270 | command: ControlCommand::CancelSwarm(swarm.id), |
| 271 | }); |
| 272 | assert!( |
| 273 | matches!(resp, ControlResponse::SwarmCancelled { swarm_id } if swarm_id == swarm.id), |
| 274 | "cancel must succeed: {:?}", |
| 275 | resp |
| 276 | ); |
| 277 | |
| 278 | let released = spine |
| 279 | .release_pending_backend_sequences(&mut backend) |
| 280 | .expect("release cancelled backend state"); |
| 281 | assert_eq!(released, BRANCHES + 1, "root + every branch released"); |
| 282 | |
| 283 | assert_fully_reclaimed(&spine, &backend, &swarm, worlds_before); |
| 284 | } |