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_cancel_readmit_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 CX1: a cancelled swarm's branches are never re-admitted after |
| 17 | //! the spine released their backend state. |
| 18 | //! |
| 19 | //! `CancelSwarm` freed the branches in the spine arena, KV and worlds, but the |
| 20 | //! scheduler keeps its own arena (same ids), so queued branches stayed live and |
| 21 | //! were admitted and decoded after the backend released them. The fix frees the |
| 22 | //! ids in the scheduler arena too, which turns queued copies stale. This test |
| 23 | //! pins that behaviour: launch a swarm with a small batch so some branches queue, cancel it, step |
| 24 | //! the spine several more times, and require |
| 25 | //! - no backend `execute_step` request for a cancelled id after its |
| 26 | //! `release_sequence`, |
| 27 | //! - empty scheduler waiting and preempted queues, |
| 28 | //! - zero leaks (arena, KV, backend state). |
| 29 | //! Every failure message carries the marker READMIT_VIOLATION. |
| 30 | //! |
| 31 | //! Mutant (outside the repo, ~/workspace/hive/PE2E-CX1/mutant.patch): the |
| 32 | //! spine no longer frees the cancelled ids in the scheduler arena, so queued |
| 33 | //! branches stay admissible. |
| 34 | //! |
| 35 | //! State isolation: same per-process AIEN_RUNTIME_STATE_DIR as |
| 36 | //! swarm_reclaim_test.rs, because the cancel sends a fixed operation id. |
| 37 | |
| 38 | use std::collections::HashSet; |
| 39 | use std::path::PathBuf; |
| 40 | use std::sync::OnceLock; |
| 41 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 42 | |
| 43 | use aien_inference_abi::{ |
| 44 | AienInferenceBackend, DecodeOutput, ModelConfig, ScheduledBatch, StepMetrics, |
| 45 | }; |
| 46 | use aien_kv_cache::create_shared_kv_manager; |
| 47 | use aien_runtime::control::{ControlCommand, ControlEnvelope, ControlResponse}; |
| 48 | use aien_runtime::spine::AienRuntimeSpine; |
| 49 | use aien_runtime::swarm::SwarmConfig; |
| 50 | use aien_scheduler::SchedulerConfig; |
| 51 | use async_trait::async_trait; |
| 52 | |
| 53 | fn fresh_state_dir() -> &'static PathBuf { |
| 54 | static DIR: OnceLock<PathBuf> = OnceLock::new(); |
| 55 | DIR.get_or_init(|| { |
| 56 | let nanos = SystemTime::now() |
| 57 | .duration_since(UNIX_EPOCH) |
| 58 | .expect("clock after epoch") |
| 59 | .as_nanos(); |
| 60 | let dir = std::env::temp_dir().join(format!( |
| 61 | "aien-swarm-cancel-readmit-test-{}-{}", |
| 62 | std::process::id(), |
| 63 | nanos |
| 64 | )); |
| 65 | let _ = std::fs::remove_dir_all(&dir); |
| 66 | std::fs::create_dir_all(&dir).expect("create fresh state dir"); |
| 67 | std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir); |
| 68 | dir |
| 69 | }) |
| 70 | } |
| 71 | |
| 72 | /// Records releases and flags any later request for a released id. |
| 73 | #[derive(Default)] |
| 74 | struct RecordingBackend { |
| 75 | released: HashSet<u64>, |
| 76 | violations: Vec<String>, |
| 77 | decodes: usize, |
| 78 | } |
| 79 | |
| 80 | #[async_trait] |
| 81 | impl AienInferenceBackend for RecordingBackend { |
| 82 | async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> { |
| 83 | Ok(()) |
| 84 | } |
| 85 | |
| 86 | async fn execute_step( |
| 87 | &mut self, |
| 88 | batch: &ScheduledBatch, |
| 89 | ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> { |
| 90 | let mut outputs = Vec::new(); |
| 91 | let ids = batch |
| 92 | .prefill_requests |
| 93 | .iter() |
| 94 | .map(|r| r.request_id) |
| 95 | .chain(batch.decode_requests.iter().copied()); |
| 96 | for id in ids { |
| 97 | if self.released.contains(&id) { |
| 98 | self.violations.push(format!( |
| 99 | "execute_step asked to run id {} after its release_sequence", |
| 100 | id |
| 101 | )); |
| 102 | } |
| 103 | self.decodes += 1; |
| 104 | outputs.push(DecodeOutput::Token { |
| 105 | request_id: id, |
| 106 | token_id: 101, |
| 107 | logprob: None, |
| 108 | }); |
| 109 | } |
| 110 | let metrics = StepMetrics { |
| 111 | prefill_tokens_processed: batch |
| 112 | .prefill_requests |
| 113 | .iter() |
| 114 | .map(|r| r.prompt_tokens.len()) |
| 115 | .sum(), |
| 116 | decode_tokens_emitted: outputs.len(), |
| 117 | step_latency_us: 0, |
| 118 | active_kv_blocks: batch.block_tables.values().map(|v| v.len()).sum(), |
| 119 | }; |
| 120 | Ok((outputs, metrics)) |
| 121 | } |
| 122 | |
| 123 | fn release_sequence(&mut self, seq_id: u64) -> Result<(), String> { |
| 124 | self.released.insert(seq_id); |
| 125 | Ok(()) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | #[tokio::test] |
| 130 | async fn cancelled_swarm_branches_are_never_readmitted() { |
| 131 | fresh_state_dir(); |
| 132 | let kv_manager = create_shared_kv_manager(256, 16); |
| 133 | // Small batch: only 2 of the 4 branches fit, the others stay queued. |
| 134 | let sched_cfg = SchedulerConfig { |
| 135 | max_batch_size: 2, |
| 136 | max_batch_tokens: 2048, |
| 137 | max_prefill_tokens: 1024, |
| 138 | prefill_chunk_size: 16, |
| 139 | chunk_prefill: true, |
| 140 | watermark_blocks: 4, |
| 141 | }; |
| 142 | let mut spine = AienRuntimeSpine::new(64, sched_cfg, kv_manager.clone()); |
| 143 | let mut backend = RecordingBackend::default(); |
| 144 | |
| 145 | let prompt: Vec<u32> = (500..540).collect(); |
| 146 | let config = SwarmConfig { |
| 147 | model_handle: 1, |
| 148 | branch_count: 4, |
| 149 | max_active_sequences: 4, |
| 150 | max_tokens_per_branch: 64, |
| 151 | root_world_id: 0, |
| 152 | priority: 1, |
| 153 | }; |
| 154 | let swarm_id = spine.launch_swarm(config, &prompt).expect("launch"); |
| 155 | |
| 156 | // Run until some branches decode and some are still queued. |
| 157 | let mut steps = 0; |
| 158 | while (backend.decodes == 0 || spine.scheduler.waiting_count() == 0) && steps < 20 { |
| 159 | steps += 1; |
| 160 | spine |
| 161 | .step(&mut backend) |
| 162 | .await |
| 163 | .unwrap_or_else(|e| panic!("READMIT_VIOLATION: pre-cancel step failed: {}", e)); |
| 164 | } |
| 165 | assert!( |
| 166 | backend.decodes > 0 && spine.scheduler.waiting_count() > 0, |
| 167 | "READMIT_VIOLATION: test setup, no queued branch before the cancel \ |
| 168 | (decodes {}, waiting {}, preempted {})", |
| 169 | backend.decodes, |
| 170 | spine.scheduler.waiting_count(), |
| 171 | spine.scheduler.preempted_count() |
| 172 | ); |
| 173 | |
| 174 | let resp = spine.handle_control_command(ControlEnvelope { |
| 175 | protocol_version: 1, |
| 176 | request_id: 1, |
| 177 | operation_id: 0xC1, |
| 178 | operator_session: 1, |
| 179 | command: ControlCommand::CancelSwarm(swarm_id), |
| 180 | }); |
| 181 | assert!( |
| 182 | matches!(resp, ControlResponse::SwarmCancelled { swarm_id: s } if s == swarm_id), |
| 183 | "READMIT_VIOLATION: test setup, cancel refused: {:?}", |
| 184 | resp |
| 185 | ); |
| 186 | |
| 187 | // Step well past the point where the first post-cancel step released |
| 188 | // the backend state and the scheduler could re-admit a queued branch. |
| 189 | for i in 0..8 { |
| 190 | spine.step(&mut backend).await.unwrap_or_else(|e| { |
| 191 | panic!( |
| 192 | "READMIT_VIOLATION: step {} after cancel failed: {}", |
| 193 | i + 1, |
| 194 | e |
| 195 | ) |
| 196 | }); |
| 197 | assert!( |
| 198 | backend.violations.is_empty(), |
| 199 | "READMIT_VIOLATION: {:?}", |
| 200 | backend.violations |
| 201 | ); |
| 202 | } |
| 203 | |
| 204 | assert!( |
| 205 | !backend.released.is_empty(), |
| 206 | "READMIT_VIOLATION: the spine never released the cancelled ids" |
| 207 | ); |
| 208 | assert_eq!( |
| 209 | spine.scheduler.waiting_count() + spine.scheduler.preempted_count(), |
| 210 | 0, |
| 211 | "READMIT_VIOLATION: cancelled ids still in scheduler queues (waiting {}, preempted {})", |
| 212 | spine.scheduler.waiting_count(), |
| 213 | spine.scheduler.preempted_count() |
| 214 | ); |
| 215 | assert_eq!( |
| 216 | spine.scheduler.running_count(), |
| 217 | 0, |
| 218 | "READMIT_VIOLATION: scheduler still runs a cancelled sequence" |
| 219 | ); |
| 220 | assert_eq!( |
| 221 | spine.arena.active_count(), |
| 222 | 0, |
| 223 | "READMIT_VIOLATION: spine arena still has active sequences" |
| 224 | ); |
| 225 | assert_eq!( |
| 226 | spine.kv_manager.read().allocated_block_count(), |
| 227 | 0, |
| 228 | "READMIT_VIOLATION: shared KV still has allocated blocks" |
| 229 | ); |
| 230 | assert_eq!(spine.swarm_manager.active_swarm_count(), 0); |
| 231 | } |