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-dual-observation / tests / snapshot_conservation.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 | //! Conservation and zero-denominator tests for the DUAL serve observation |
| 17 | //! snapshot, over the real scheduler and KV manager with the mock backend. |
| 18 | //! |
| 19 | //! Every assertion compares two existing ledgers of the production state |
| 20 | //! machine against each other; nothing here is a model of what they should |
| 21 | //! be. The workload submits requests only through `submit_request` and never |
| 22 | //! cancels, so the sequence ledgers close exactly (see `lib.rs` field docs |
| 23 | //! for the two cases, fork children and cancellation, where |
| 24 | //! `admitted_requests` is not the right denominator). |
| 25 | |
| 26 | use aien_abi_core::{SamplingParams, ScheduledBatch, SequenceRequest, StepMetrics}; |
| 27 | use aien_dual_observation::{DeltaError, ObservationDelta, ServeObservationSnapshot}; |
| 28 | use aien_inference_abi::MockInferenceBackend; |
| 29 | use aien_kv_cache::create_shared_kv_manager; |
| 30 | use aien_scheduler::{AienScheduler, SchedulerConfig}; |
| 31 | |
| 32 | fn request(id: u64, prompt_len: usize, priority: u8, max_tokens: usize) -> SequenceRequest { |
| 33 | SequenceRequest { |
| 34 | request_id: id, |
| 35 | prompt_tokens: (0..prompt_len as u32).collect(), |
| 36 | sampling_params: SamplingParams { |
| 37 | temperature: 0.0, |
| 38 | top_p: 1.0, |
| 39 | max_tokens, |
| 40 | stop_token_ids: vec![], |
| 41 | }, |
| 42 | arrival_time_ns: 0, |
| 43 | priority, |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn config(max_batch_size: usize, watermark_blocks: usize) -> SchedulerConfig { |
| 48 | SchedulerConfig { |
| 49 | max_batch_size, |
| 50 | max_batch_tokens: 1024, |
| 51 | max_prefill_tokens: 100, |
| 52 | prefill_chunk_size: 64, |
| 53 | chunk_prefill: true, |
| 54 | watermark_blocks, |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Checks that hold for every snapshot of a scheduler fed only through |
| 59 | /// `submit_request` without cancellation. |
| 60 | fn assert_conserved(s: &ServeObservationSnapshot, where_: &str) { |
| 61 | // KV: the free list and the refcount ledger partition the pool. |
| 62 | assert_eq!( |
| 63 | s.kv_physical_pages + s.kv_free_blocks, |
| 64 | s.kv_total_blocks, |
| 65 | "{where_}: physical (ref_count>0) + free == total" |
| 66 | ); |
| 67 | assert_eq!( |
| 68 | s.kv_allocated_blocks + s.kv_free_blocks, |
| 69 | s.kv_total_blocks, |
| 70 | "{where_}: allocated + free == total" |
| 71 | ); |
| 72 | assert_eq!(s.kv_used_blocks, s.kv_physical_pages, "{where_}"); |
| 73 | assert_eq!( |
| 74 | s.kv_shared_pages + s.kv_private_pages, |
| 75 | s.kv_physical_pages, |
| 76 | "{where_}: shared + private == physical" |
| 77 | ); |
| 78 | assert!(s.kv_logical_pages >= s.kv_physical_pages, "{where_}"); |
| 79 | // Sequences: the arena holds exactly the queued and running records. |
| 80 | assert_eq!( |
| 81 | s.arena_active, |
| 82 | s.running + s.waiting + s.preempted, |
| 83 | "{where_}: arena == running + waiting + preempted" |
| 84 | ); |
| 85 | // Lifetime ledger: every admitted request is finished or still held. |
| 86 | assert_eq!( |
| 87 | s.admitted_requests, |
| 88 | s.finished_requests + (s.running + s.waiting + s.preempted) as u64, |
| 89 | "{where_}: admitted == finished + held" |
| 90 | ); |
| 91 | // Densities are the exact counters. |
| 92 | assert_eq!(s.kv_block_density.numerator, s.kv_allocated_blocks); |
| 93 | assert_eq!(s.kv_block_density.denominator, s.kv_total_blocks); |
| 94 | assert_eq!(s.running_slot_density.numerator, s.running); |
| 95 | assert_eq!(s.running_slot_density.denominator, s.max_batch_size); |
| 96 | assert_eq!( |
| 97 | s.kv_sharing_density.numerator, |
| 98 | s.kv_logical_pages - s.kv_physical_pages |
| 99 | ); |
| 100 | assert_eq!(s.kv_sharing_density.denominator, s.kv_logical_pages); |
| 101 | assert_eq!( |
| 102 | s.kv_below_watermark, |
| 103 | s.kv_free_blocks < s.watermark_blocks, |
| 104 | "{where_}" |
| 105 | ); |
| 106 | if let Some(step) = &s.last_step { |
| 107 | // StepMetrics::active_kv_blocks is allocated_block_count after the |
| 108 | // step, read before the caller captured; a capture right after the |
| 109 | // step sees the same number. |
| 110 | assert_eq!(step.active_kv_blocks, s.kv_allocated_blocks, "{where_}"); |
| 111 | } |
| 112 | if let Some(b) = &s.last_batch { |
| 113 | assert_eq!( |
| 114 | s.batch_slot_density.numerator, |
| 115 | b.prefill_requests + b.decode_requests |
| 116 | ); |
| 117 | assert_eq!(s.batch_token_density.numerator, b.batch_tokens); |
| 118 | assert!(b.prefill_requests + b.decode_requests <= s.max_batch_size); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// Runs a scheduler through a mixed workload (admission, chunked prefill, |
| 123 | /// watermark preemption, completion) and snapshots after every step. |
| 124 | async fn run_and_snapshot( |
| 125 | kv_blocks: usize, |
| 126 | cfg: SchedulerConfig, |
| 127 | requests: Vec<SequenceRequest>, |
| 128 | max_steps: usize, |
| 129 | ) -> Vec<ServeObservationSnapshot> { |
| 130 | let kv = create_shared_kv_manager(kv_blocks, 16); |
| 131 | let mut scheduler = AienScheduler::new(cfg, kv.clone()); |
| 132 | let mut backend = MockInferenceBackend::new(0); |
| 133 | let mut snaps = Vec::new(); |
| 134 | |
| 135 | snaps.push(ServeObservationSnapshot::capture( |
| 136 | &scheduler, |
| 137 | &kv.read(), |
| 138 | None, |
| 139 | None, |
| 140 | )); |
| 141 | for r in requests { |
| 142 | scheduler.submit_request(r); |
| 143 | snaps.push(ServeObservationSnapshot::capture( |
| 144 | &scheduler, |
| 145 | &kv.read(), |
| 146 | None, |
| 147 | None, |
| 148 | )); |
| 149 | } |
| 150 | let mut steps = 0; |
| 151 | while steps < max_steps |
| 152 | && (scheduler.waiting_count() + scheduler.running_count() + scheduler.preempted_count() > 0) |
| 153 | { |
| 154 | steps += 1; |
| 155 | let result = scheduler.step(&mut backend).await; |
| 156 | let metrics: Option<StepMetrics> = match result { |
| 157 | Ok(Some((_, m))) => Some(m), |
| 158 | Ok(None) => None, |
| 159 | Err(e) => panic!("step error in conservation workload: {e}"), |
| 160 | }; |
| 161 | snaps.push(ServeObservationSnapshot::capture( |
| 162 | &scheduler, |
| 163 | &kv.read(), |
| 164 | metrics.as_ref(), |
| 165 | None, |
| 166 | )); |
| 167 | } |
| 168 | assert_eq!(scheduler.running_count(), 0, "workload must drain"); |
| 169 | snaps |
| 170 | } |
| 171 | |
| 172 | fn mixed_requests() -> Vec<SequenceRequest> { |
| 173 | vec![ |
| 174 | request(1, 20, 3, 3), |
| 175 | request(2, 150, 1, 2), |
| 176 | request(3, 7, 0, 4), |
| 177 | request(4, 64, 2, 1), |
| 178 | request(5, 33, 1, 2), |
| 179 | ] |
| 180 | } |
| 181 | |
| 182 | #[tokio::test] |
| 183 | async fn ledgers_close_at_every_snapshot_under_plenty() { |
| 184 | let snaps = run_and_snapshot(256, config(8, 2), mixed_requests(), 64).await; |
| 185 | assert!(snaps.len() > 6); |
| 186 | for (i, s) in snaps.iter().enumerate() { |
| 187 | assert_conserved(s, &format!("plenty snapshot {i}")); |
| 188 | } |
| 189 | let last = snaps.last().unwrap(); |
| 190 | assert_eq!(last.kv_allocated_blocks, 0); |
| 191 | assert_eq!(last.arena_active, 0); |
| 192 | assert_eq!(last.finished_requests, 5); |
| 193 | assert_eq!(last.kv_block_density.value(), Some(0.0)); |
| 194 | } |
| 195 | |
| 196 | #[tokio::test] |
| 197 | async fn ledgers_close_at_every_snapshot_under_watermark_pressure() { |
| 198 | // 6-block pool, watermark 3: two 32-token prompts fill 4 blocks, the pool |
| 199 | // drops below the watermark and the lower priority sequence is preempted. |
| 200 | let cfg = SchedulerConfig { |
| 201 | max_batch_size: 4, |
| 202 | max_batch_tokens: 1024, |
| 203 | max_prefill_tokens: 512, |
| 204 | prefill_chunk_size: 128, |
| 205 | chunk_prefill: false, |
| 206 | watermark_blocks: 3, |
| 207 | }; |
| 208 | let reqs = vec![request(1, 32, 3, 4), request(2, 32, 1, 4)]; |
| 209 | let snaps = run_and_snapshot(6, cfg, reqs, 64).await; |
| 210 | for (i, s) in snaps.iter().enumerate() { |
| 211 | assert_conserved(s, &format!("pressure snapshot {i}")); |
| 212 | } |
| 213 | assert!( |
| 214 | snaps.iter().any(|s| s.kv_below_watermark && s.running > 0), |
| 215 | "the workload must cross the watermark while something runs" |
| 216 | ); |
| 217 | let last = snaps.last().unwrap(); |
| 218 | assert!( |
| 219 | last.preempted_requests >= 1, |
| 220 | "a preemption must have happened" |
| 221 | ); |
| 222 | assert_eq!(last.finished_requests, 2); |
| 223 | assert_eq!(last.kv_allocated_blocks, 0); |
| 224 | } |
| 225 | |
| 226 | #[tokio::test] |
| 227 | async fn deltas_are_exact_counter_differences() { |
| 228 | let snaps = run_and_snapshot(256, config(8, 2), mixed_requests(), 64).await; |
| 229 | let first = &snaps[0]; |
| 230 | let after_submits = &snaps[5]; |
| 231 | let last = snaps.last().unwrap(); |
| 232 | |
| 233 | let d = ObservationDelta::between(first, after_submits).unwrap(); |
| 234 | assert_eq!(d.steps, 0); |
| 235 | assert_eq!(d.arrivals, 5); |
| 236 | assert_eq!(d.completions, 0); |
| 237 | assert_eq!(d.waiting_change, 5); |
| 238 | |
| 239 | let d = ObservationDelta::between(after_submits, last).unwrap(); |
| 240 | assert_eq!(d.arrivals, 0); |
| 241 | assert_eq!(d.completions, 5); |
| 242 | assert_eq!(d.steps, last.generation - after_submits.generation); |
| 243 | assert_eq!(d.waiting_change, -5); |
| 244 | assert_eq!(d.kv_allocated_change, 0); |
| 245 | assert_eq!(d.prefill_tokens, last.total_prefill_tokens); |
| 246 | assert_eq!(d.decode_tokens, last.total_decode_tokens); |
| 247 | // Prefill tokens over the run equal the prompt tokens submitted. |
| 248 | assert_eq!(d.prefill_tokens, 20 + 150 + 7 + 64 + 33); |
| 249 | |
| 250 | // Consecutive deltas sum to the whole. |
| 251 | let mut arrivals = 0; |
| 252 | let mut completions = 0; |
| 253 | let mut steps = 0; |
| 254 | for w in snaps.windows(2) { |
| 255 | let d = ObservationDelta::between(&w[0], &w[1]).unwrap(); |
| 256 | arrivals += d.arrivals; |
| 257 | completions += d.completions; |
| 258 | steps += d.steps; |
| 259 | } |
| 260 | assert_eq!(arrivals, 5); |
| 261 | assert_eq!(completions, 5); |
| 262 | assert_eq!(steps, last.generation); |
| 263 | } |
| 264 | |
| 265 | #[tokio::test] |
| 266 | async fn reversed_or_foreign_snapshots_are_refused() { |
| 267 | let snaps = run_and_snapshot(256, config(8, 2), mixed_requests(), 64).await; |
| 268 | let first = &snaps[0]; |
| 269 | let last = snaps.last().unwrap(); |
| 270 | assert!(matches!( |
| 271 | ObservationDelta::between(last, first), |
| 272 | Err(DeltaError::GenerationWentBackwards { .. }) |
| 273 | )); |
| 274 | |
| 275 | let other = run_and_snapshot(32, config(8, 2), vec![request(9, 5, 1, 1)], 8).await; |
| 276 | assert!(matches!( |
| 277 | ObservationDelta::between(first, other.last().unwrap()), |
| 278 | Err(DeltaError::PoolSizeChanged { .. }) |
| 279 | )); |
| 280 | |
| 281 | // Same pool size, more steps (60 decode tokens) but fewer admissions: the |
| 282 | // generation moves forward while the lifetime counter went backwards. |
| 283 | let fewer = run_and_snapshot(256, config(8, 2), vec![request(9, 5, 1, 60)], 80).await; |
| 284 | assert!(fewer.last().unwrap().generation > last.generation); |
| 285 | assert!(matches!( |
| 286 | ObservationDelta::between(last, fewer.last().unwrap()), |
| 287 | Err(DeltaError::CounterWentBackwards { |
| 288 | counter: "admitted_requests", |
| 289 | .. |
| 290 | }) |
| 291 | )); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn zero_capacity_densities_are_none_not_zero() { |
| 296 | let kv = create_shared_kv_manager(0, 16); |
| 297 | let cfg = SchedulerConfig { |
| 298 | max_batch_size: 0, |
| 299 | max_batch_tokens: 0, |
| 300 | max_prefill_tokens: 0, |
| 301 | prefill_chunk_size: 0, |
| 302 | chunk_prefill: true, |
| 303 | watermark_blocks: 0, |
| 304 | }; |
| 305 | let scheduler = AienScheduler::new(cfg, kv.clone()); |
| 306 | let s = ServeObservationSnapshot::capture(&scheduler, &kv.read(), None, None); |
| 307 | assert_eq!(s.kv_total_blocks, 0); |
| 308 | assert_eq!(s.kv_block_density.value(), None); |
| 309 | assert_eq!(s.kv_sharing_density.value(), None); |
| 310 | assert_eq!(s.running_slot_density.value(), None); |
| 311 | assert_eq!(s.batch_slot_density.value(), None); |
| 312 | assert_eq!(s.batch_token_density.value(), None); |
| 313 | assert!(!s.kv_below_watermark); |
| 314 | assert_eq!(s.last_step, None); |
| 315 | assert_eq!(s.last_batch, None); |
| 316 | assert_conserved(&s, "zero capacity"); |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn batch_reading_copies_sizes_and_the_token_sum() { |
| 321 | let kv = create_shared_kv_manager(16, 16); |
| 322 | let scheduler = AienScheduler::new(config(4, 1), kv.clone()); |
| 323 | let batch = ScheduledBatch { |
| 324 | prefill_requests: vec![request(1, 10, 1, 1), request(2, 5, 1, 1)], |
| 325 | decode_requests: vec![3, 4, 5], |
| 326 | block_tables: Default::default(), |
| 327 | step_id: 42, |
| 328 | }; |
| 329 | let s = ServeObservationSnapshot::capture(&scheduler, &kv.read(), None, Some(&batch)); |
| 330 | let b = s.last_batch.unwrap(); |
| 331 | assert_eq!(b.step_id, 42); |
| 332 | assert_eq!(b.prefill_requests, 2); |
| 333 | assert_eq!(b.decode_requests, 3); |
| 334 | assert_eq!(b.batch_tokens, 15 + 3); |
| 335 | assert_eq!(s.batch_slot_density.value(), Some(5.0 / 4.0)); |
| 336 | assert_eq!(s.batch_token_density.value(), Some(18.0 / 1024.0)); |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn snapshot_serializes_and_round_trips() { |
| 341 | let kv = create_shared_kv_manager(8, 16); |
| 342 | let scheduler = AienScheduler::new(config(4, 1), kv.clone()); |
| 343 | let s = ServeObservationSnapshot::capture(&scheduler, &kv.read(), None, None); |
| 344 | let json = serde_json::to_string(&s).unwrap(); |
| 345 | let back: ServeObservationSnapshot = serde_json::from_str(&json).unwrap(); |
| 346 | assert_eq!(back, s); |
| 347 | } |