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 / preempt_resume_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 | //! A sequence preempted under KV pressure must resume without re-emitting |
| 17 | //! tokens. |
| 18 | //! |
| 19 | //! Runs the real spine, scheduler and native backend over the CPU reference |
| 20 | //! tensor backend, built through the daemon's factory |
| 21 | //! (`aien_runtime::shared_kv::build_shared_kv_runtime`). No persistence. |
| 22 | //! |
| 23 | //! Before the fix, the scheduler kept a preempted sequence's generated tokens |
| 24 | //! but re-prefilled only its prompt, and the backend's per-sequence state was |
| 25 | //! never released on preemption. The resume then either re-sampled and |
| 26 | //! re-emitted tokens the sink already had, or the backend refused a decode at |
| 27 | //! a stale position. |
| 28 | |
| 29 | use std::collections::HashMap; |
| 30 | use std::sync::Arc; |
| 31 | use std::time::{Duration, Instant}; |
| 32 | |
| 33 | use aien_abi_core::{ModelConfig, SamplingParams}; |
| 34 | use aien_inference_abi::{NativeTransformerBackend, ReferenceCpuBackend, TransformerWeights}; |
| 35 | use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; |
| 36 | use aien_runtime::spine::AienRuntimeSpine; |
| 37 | use aien_scheduler::{ |
| 38 | ChannelCompletionSink, CompletionEvent, CompletionSinkId, SchedulerConfig, SequenceId, |
| 39 | SequencePhase, |
| 40 | }; |
| 41 | use tokio::sync::mpsc::UnboundedReceiver; |
| 42 | |
| 43 | const HANG_GUARD: Duration = Duration::from_secs(30); |
| 44 | |
| 45 | fn model() -> ModelConfig { |
| 46 | ModelConfig { |
| 47 | model_id: "preempt-resume-reference".to_string(), |
| 48 | max_sequence_length: 256, |
| 49 | block_size: 4, |
| 50 | num_layers: 3, |
| 51 | num_heads: 4, |
| 52 | head_dim: 8, |
| 53 | num_kv_heads: 2, |
| 54 | hidden_dim: 32, |
| 55 | intermediate_dim: 64, |
| 56 | vocab_size: 97, |
| 57 | rms_norm_eps: 1e-5, |
| 58 | rope_theta: 10000.0, |
| 59 | rope_scaling: None, |
| 60 | tie_word_embeddings: false, |
| 61 | // Outside the 97-token vocabulary: no sampled token ends a turn early |
| 62 | // (an empty list means the legacy stop set 0, 1, 2). |
| 63 | eos_token_ids: vec![1000], |
| 64 | qk_norm: false, |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | struct Rig { |
| 69 | spine: AienRuntimeSpine, |
| 70 | backend: NativeTransformerBackend, |
| 71 | sink: CompletionSinkId, |
| 72 | rx: UnboundedReceiver<CompletionEvent>, |
| 73 | /// Tokens streamed to the completion sink, per sequence id. |
| 74 | tokens: HashMap<u64, Vec<u32>>, |
| 75 | steps: u64, |
| 76 | } |
| 77 | |
| 78 | fn rig(total_blocks: usize, watermark_blocks: usize, max_batch_size: usize) -> Rig { |
| 79 | let config = model(); |
| 80 | let weights = TransformerWeights::reference_test_weights(&config); |
| 81 | let (mut spine, backend) = build_shared_kv_runtime( |
| 82 | weights, |
| 83 | Arc::new(ReferenceCpuBackend::new()), |
| 84 | SchedulerConfig { |
| 85 | max_batch_size, |
| 86 | max_batch_tokens: 4096, |
| 87 | max_prefill_tokens: 4096, |
| 88 | prefill_chunk_size: 4096, |
| 89 | chunk_prefill: true, |
| 90 | watermark_blocks, |
| 91 | }, |
| 92 | SharedKvSizing { |
| 93 | arena_capacity: 64, |
| 94 | total_blocks, |
| 95 | }, |
| 96 | ) |
| 97 | .expect("runtime"); |
| 98 | let (sink, rx) = ChannelCompletionSink::channel(); |
| 99 | let sink = spine.register_completion_sink(Arc::new(sink)); |
| 100 | Rig { |
| 101 | spine, |
| 102 | backend, |
| 103 | sink, |
| 104 | rx, |
| 105 | tokens: HashMap::new(), |
| 106 | steps: 0, |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn phase_of(r: &Rig, seq: u64) -> Option<SequencePhase> { |
| 111 | let id = SequenceId::from_u64(seq).ok()?; |
| 112 | r.spine.scheduler.arena().get(id).map(|rec| rec.phase) |
| 113 | } |
| 114 | |
| 115 | fn finished(r: &Rig, seq: u64) -> bool { |
| 116 | phase_of(r, seq).is_none() |
| 117 | } |
| 118 | |
| 119 | fn emitted(r: &Rig, seq: u64) -> usize { |
| 120 | r.tokens.get(&seq).map_or(0, Vec::len) |
| 121 | } |
| 122 | |
| 123 | fn toks(r: &Rig, seq: u64) -> Vec<u32> { |
| 124 | r.tokens.get(&seq).cloned().unwrap_or_default() |
| 125 | } |
| 126 | |
| 127 | fn submit(r: &mut Rig, prompt: &[u32], max_tokens: usize) -> u64 { |
| 128 | r.spine |
| 129 | .submit_work( |
| 130 | Arc::from(prompt.to_vec()), |
| 131 | SamplingParams { |
| 132 | temperature: 0.0, |
| 133 | top_p: 1.0, |
| 134 | max_tokens, |
| 135 | stop_token_ids: vec![], |
| 136 | }, |
| 137 | 1, |
| 138 | Some(r.sink), |
| 139 | ) |
| 140 | .expect("submit") |
| 141 | } |
| 142 | |
| 143 | async fn step(r: &mut Rig) { |
| 144 | r.spine.step(&mut r.backend).await.expect("step"); |
| 145 | r.steps += 1; |
| 146 | while let Ok(ev) = r.rx.try_recv() { |
| 147 | if let CompletionEvent::Token { seq_id, token } = ev { |
| 148 | r.tokens.entry(seq_id.to_u64()).or_default().push(token); |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | /// Steps until `cond` holds, at most `max_steps` steps. |
| 154 | async fn step_until(r: &mut Rig, what: &str, max_steps: u64, cond: impl Fn(&Rig) -> bool) { |
| 155 | let t0 = Instant::now(); |
| 156 | let start = r.steps; |
| 157 | loop { |
| 158 | if cond(r) { |
| 159 | return; |
| 160 | } |
| 161 | assert!( |
| 162 | r.steps - start < max_steps, |
| 163 | "no progress within {max_steps} steps: {what}" |
| 164 | ); |
| 165 | assert!(t0.elapsed() < HANG_GUARD, "hang guard: {what}"); |
| 166 | step(r).await; |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /// The greedy tokens of `prompt` on a roomy runtime that never preempts. |
| 171 | async fn uninterrupted(prompt: &[u32], max_tokens: usize) -> Vec<u32> { |
| 172 | let mut r = rig(64, 0, 16); |
| 173 | let seq = submit(&mut r, prompt, max_tokens); |
| 174 | step_until(&mut r, "uninterrupted run", 500, |r| finished(r, seq)).await; |
| 175 | assert_eq!(r.spine.scheduler.metrics().preempted_requests, 0); |
| 176 | let t = toks(&r, seq); |
| 177 | assert_eq!(t.len(), max_tokens, "uninterrupted run emitted every token"); |
| 178 | t |
| 179 | } |
| 180 | |
| 181 | fn prompt_a() -> Vec<u32> { |
| 182 | vec![5, 17, 42, 3, 88, 61, 9, 23, 70, 11, 36, 2, 44, 19, 80] |
| 183 | } |
| 184 | |
| 185 | fn prompt_b() -> Vec<u32> { |
| 186 | vec![31, 7, 64, 12, 90, 27, 55, 4, 73, 18, 39, 66, 21, 85, 50] |
| 187 | } |
| 188 | |
| 189 | /// A sequence preempted by the watermark check and resumed later delivers |
| 190 | /// every token to its sink exactly once, and its output equals a run that was |
| 191 | /// never preempted. |
| 192 | /// |
| 193 | /// Geometry: a 10-block pool with a watermark of 3. Request A (15-token |
| 194 | /// prompt, 4 blocks) decodes alone for a few steps. Request B (another 4 |
| 195 | /// blocks) is admitted while 3 or more blocks are free, which leaves fewer |
| 196 | /// than the watermark, so the next step preempts A (the lowest-priority |
| 197 | /// running sequence, first in running order). A needs 4 blocks plus the |
| 198 | /// watermark headroom to come back, so it resumes only after B finishes. |
| 199 | #[tokio::test] |
| 200 | async fn preempted_sequence_resumes_without_re_emitting_tokens() { |
| 201 | let max_a = 12; |
| 202 | let max_b = 4; |
| 203 | let want_a = uninterrupted(&prompt_a(), max_a).await; |
| 204 | let want_b = uninterrupted(&prompt_b(), max_b).await; |
| 205 | |
| 206 | let mut r = rig(10, 3, 4); |
| 207 | let a = submit(&mut r, &prompt_a(), max_a); |
| 208 | step_until(&mut r, "A emitted three tokens", 50, |r| emitted(r, a) >= 3).await; |
| 209 | let emitted_before = emitted(&r, a); |
| 210 | assert!(!finished(&r, a), "A still running"); |
| 211 | let b = submit(&mut r, &prompt_b(), max_b); |
| 212 | step_until(&mut r, "A preempted", 50, |r| { |
| 213 | r.spine.scheduler.metrics().preempted_requests >= 1 |
| 214 | }) |
| 215 | .await; |
| 216 | assert_eq!( |
| 217 | phase_of(&r, a), |
| 218 | Some(SequencePhase::Preempted), |
| 219 | "A is the preempted sequence" |
| 220 | ); |
| 221 | step_until(&mut r, "A and B finished", 500, |r| { |
| 222 | finished(r, a) && finished(r, b) |
| 223 | }) |
| 224 | .await; |
| 225 | |
| 226 | assert_eq!(toks(&r, b), want_b, "B greedy"); |
| 227 | let got_a = toks(&r, a); |
| 228 | assert!( |
| 229 | emitted_before < got_a.len(), |
| 230 | "A emitted more after resuming" |
| 231 | ); |
| 232 | assert_eq!( |
| 233 | got_a.len(), |
| 234 | max_a, |
| 235 | "every token of A reached the sink exactly once: {got_a:?}" |
| 236 | ); |
| 237 | assert_eq!( |
| 238 | got_a, want_a, |
| 239 | "A after preemption equals the uninterrupted run" |
| 240 | ); |
| 241 | let kv = r.spine.kv_manager.read(); |
| 242 | assert_eq!( |
| 243 | kv.free_block_count(), |
| 244 | kv.total_block_count(), |
| 245 | "every block returned at the end" |
| 246 | ); |
| 247 | } |