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 / src / sequence.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 | //! SequenceArena and Generational Sequence Allocation |
| 17 | //! Enforces single-mutable-owner discipline for the scheduler thread. |
| 18 | |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | |
| 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 22 | pub struct SequenceId { |
| 23 | pub slot: u32, |
| 24 | pub generation: u32, |
| 25 | } |
| 26 | |
| 27 | impl SequenceId { |
| 28 | pub fn new(slot: u32, generation: u32) -> Self { |
| 29 | Self { slot, generation } |
| 30 | } |
| 31 | |
| 32 | #[inline] |
| 33 | pub fn as_u64(&self) -> u64 { |
| 34 | ((self.slot as u64) << 32) | (self.generation as u64) |
| 35 | } |
| 36 | |
| 37 | #[inline] |
| 38 | pub fn from_u64(val: u64) -> Self { |
| 39 | Self { |
| 40 | slot: (val >> 32) as u32, |
| 41 | generation: (val & 0xFFFF_FFFF) as u32, |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl std::fmt::Display for SequenceId { |
| 47 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 48 | write!(f, "seq_{}:{}", self.slot, self.generation) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 53 | pub enum SequenceState { |
| 54 | Ready, |
| 55 | Prefill, |
| 56 | Decode, |
| 57 | BlockedOnTool, |
| 58 | Cancelled, |
| 59 | Completed, |
| 60 | } |
| 61 | |
| 62 | #[repr(C, align(64))] |
| 63 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 64 | pub struct SequenceRecord { |
| 65 | pub id: SequenceId, |
| 66 | pub parent_id: Option<SequenceId>, |
| 67 | pub world_id: u64, |
| 68 | pub priority: u8, |
| 69 | pub state: SequenceState, |
| 70 | pub context_id: u64, |
| 71 | pub block_table_id: u32, |
| 72 | pub prefill_cursor: usize, |
| 73 | pub generated_tokens: usize, |
| 74 | pub arrival_ticks: u64, |
| 75 | pub deadline_ticks: Option<u64>, |
| 76 | } |
| 77 | |
| 78 | pub struct SequenceSlot { |
| 79 | pub generation: u32, |
| 80 | /// Set when the generation reached u32::MAX and was freed. A retired slot is never reused, |
| 81 | /// so a stale id can never match again (same policy as the scheduler arena). |
| 82 | pub retired: bool, |
| 83 | pub record: Option<SequenceRecord>, |
| 84 | } |
| 85 | |
| 86 | /// Contiguous SequenceArena owned exclusively by the Scheduler thread. |
| 87 | pub struct SequenceArena { |
| 88 | slots: Vec<SequenceSlot>, |
| 89 | free_slots: Vec<u32>, |
| 90 | active_count: usize, |
| 91 | capacity: usize, |
| 92 | retired_slots_count: usize, |
| 93 | } |
| 94 | |
| 95 | impl SequenceArena { |
| 96 | pub fn new(capacity: usize) -> Self { |
| 97 | let mut slots = Vec::with_capacity(capacity); |
| 98 | let mut free_slots = Vec::with_capacity(capacity); |
| 99 | |
| 100 | for i in 0..capacity { |
| 101 | slots.push(SequenceSlot { |
| 102 | generation: 1, |
| 103 | retired: false, |
| 104 | record: None, |
| 105 | }); |
| 106 | free_slots.push(i as u32); |
| 107 | } |
| 108 | free_slots.reverse(); |
| 109 | |
| 110 | Self { |
| 111 | slots, |
| 112 | free_slots, |
| 113 | active_count: 0, |
| 114 | capacity, |
| 115 | retired_slots_count: 0, |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// Test-only: start every slot at `generation` so the u32::MAX boundary is reachable. |
| 120 | #[cfg(test)] |
| 121 | pub(crate) fn with_start_generation(capacity: usize, generation: u32) -> Self { |
| 122 | let mut arena = Self::new(capacity); |
| 123 | for slot in &mut arena.slots { |
| 124 | slot.generation = generation; |
| 125 | } |
| 126 | arena |
| 127 | } |
| 128 | |
| 129 | /// Number of slots permanently retired after exhausting their generation space. |
| 130 | pub fn retired_slots(&self) -> usize { |
| 131 | self.retired_slots_count |
| 132 | } |
| 133 | |
| 134 | pub fn allocate( |
| 135 | &mut self, |
| 136 | world_id: u64, |
| 137 | context_id: u64, |
| 138 | priority: u8, |
| 139 | arrival_ticks: u64, |
| 140 | ) -> Result<SequenceId, String> { |
| 141 | let slot_idx = self |
| 142 | .free_slots |
| 143 | .pop() |
| 144 | .ok_or_else(|| format!("SequenceArena capacity exhausted ({})", self.capacity))?; |
| 145 | |
| 146 | let slot = &mut self.slots[slot_idx as usize]; |
| 147 | let id = SequenceId::new(slot_idx, slot.generation); |
| 148 | |
| 149 | slot.record = Some(SequenceRecord { |
| 150 | id, |
| 151 | parent_id: None, |
| 152 | world_id, |
| 153 | priority, |
| 154 | state: SequenceState::Ready, |
| 155 | context_id, |
| 156 | block_table_id: slot_idx, |
| 157 | prefill_cursor: 0, |
| 158 | generated_tokens: 0, |
| 159 | arrival_ticks, |
| 160 | deadline_ticks: None, |
| 161 | }); |
| 162 | |
| 163 | self.active_count += 1; |
| 164 | Ok(id) |
| 165 | } |
| 166 | |
| 167 | pub fn fork( |
| 168 | &mut self, |
| 169 | parent_id: SequenceId, |
| 170 | child_world_id: u64, |
| 171 | arrival_ticks: u64, |
| 172 | ) -> Result<SequenceId, String> { |
| 173 | let (parent_context_id, parent_priority, parent_prefill, parent_generated) = { |
| 174 | let parent = self |
| 175 | .get(parent_id) |
| 176 | .ok_or_else(|| format!("Parent sequence {} not found or stale", parent_id))?; |
| 177 | ( |
| 178 | parent.context_id, |
| 179 | parent.priority, |
| 180 | parent.prefill_cursor, |
| 181 | parent.generated_tokens, |
| 182 | ) |
| 183 | }; |
| 184 | |
| 185 | let child_slot = self.free_slots.pop().ok_or_else(|| { |
| 186 | format!( |
| 187 | "SequenceArena capacity exhausted on fork ({})", |
| 188 | self.capacity |
| 189 | ) |
| 190 | })?; |
| 191 | |
| 192 | let slot = &mut self.slots[child_slot as usize]; |
| 193 | let child_id = SequenceId::new(child_slot, slot.generation); |
| 194 | |
| 195 | slot.record = Some(SequenceRecord { |
| 196 | id: child_id, |
| 197 | parent_id: Some(parent_id), |
| 198 | world_id: child_world_id, |
| 199 | priority: parent_priority, |
| 200 | state: SequenceState::Decode, |
| 201 | context_id: parent_context_id, |
| 202 | block_table_id: child_slot, |
| 203 | prefill_cursor: parent_prefill, |
| 204 | generated_tokens: parent_generated, |
| 205 | arrival_ticks, |
| 206 | deadline_ticks: None, |
| 207 | }); |
| 208 | |
| 209 | self.active_count += 1; |
| 210 | Ok(child_id) |
| 211 | } |
| 212 | |
| 213 | #[inline] |
| 214 | pub fn get(&self, id: SequenceId) -> Option<&SequenceRecord> { |
| 215 | let slot = self.slots.get(id.slot as usize)?; |
| 216 | if slot.generation == id.generation { |
| 217 | slot.record.as_ref() |
| 218 | } else { |
| 219 | None |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | #[inline] |
| 224 | pub fn get_mut(&mut self, id: SequenceId) -> Option<&mut SequenceRecord> { |
| 225 | let slot = self.slots.get_mut(id.slot as usize)?; |
| 226 | if slot.generation == id.generation { |
| 227 | slot.record.as_mut() |
| 228 | } else { |
| 229 | None |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | pub fn free(&mut self, id: SequenceId) -> bool { |
| 234 | if let Some(slot) = self.slots.get_mut(id.slot as usize) { |
| 235 | if slot.generation == id.generation && slot.record.is_some() { |
| 236 | slot.record = None; |
| 237 | // Advance the generation to invalidate in-flight references (ABA protection). |
| 238 | // At u32::MAX the slot is retired instead of wrapping, so no id can ever repeat. |
| 239 | if slot.generation == u32::MAX { |
| 240 | slot.retired = true; |
| 241 | self.retired_slots_count += 1; |
| 242 | } else { |
| 243 | slot.generation += 1; |
| 244 | self.free_slots.push(id.slot); |
| 245 | } |
| 246 | self.active_count = self.active_count.saturating_sub(1); |
| 247 | return true; |
| 248 | } |
| 249 | } |
| 250 | false |
| 251 | } |
| 252 | |
| 253 | pub fn validate(&self, id: SequenceId) -> bool { |
| 254 | self.get(id).is_some() |
| 255 | } |
| 256 | |
| 257 | pub fn active_count(&self) -> usize { |
| 258 | self.active_count |
| 259 | } |
| 260 | |
| 261 | pub fn capacity(&self) -> usize { |
| 262 | self.capacity |
| 263 | } |
| 264 | |
| 265 | pub fn iter_active(&self) -> impl Iterator<Item = &SequenceRecord> { |
| 266 | self.slots.iter().filter_map(|s| s.record.as_ref()) |
| 267 | } |
| 268 | |
| 269 | pub fn iter_active_mut(&mut self) -> impl Iterator<Item = &mut SequenceRecord> { |
| 270 | self.slots.iter_mut().filter_map(|s| s.record.as_mut()) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | #[cfg(test)] |
| 275 | mod tests { |
| 276 | use super::*; |
| 277 | |
| 278 | #[test] |
| 279 | fn free_below_max_advances_generation_and_reuses_slot() { |
| 280 | let mut arena = SequenceArena::with_start_generation(1, u32::MAX - 1); |
| 281 | let id = arena.allocate(1, 1, 0, 0).unwrap(); |
| 282 | assert_eq!(id.generation, u32::MAX - 1); |
| 283 | assert!(arena.free(id)); |
| 284 | assert_eq!(arena.retired_slots(), 0); |
| 285 | let next = arena.allocate(1, 1, 0, 0).unwrap(); |
| 286 | assert_eq!(next.slot, id.slot); |
| 287 | assert_eq!(next.generation, u32::MAX); |
| 288 | assert!(!arena.validate(id)); |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn free_at_max_retires_slot_and_never_resurrects_stale_id() { |
| 293 | let mut arena = SequenceArena::with_start_generation(2, u32::MAX); |
| 294 | let id = arena.allocate(1, 1, 0, 0).unwrap(); |
| 295 | assert_eq!(id.generation, u32::MAX); |
| 296 | assert!(arena.free(id)); |
| 297 | assert_eq!(arena.retired_slots(), 1); |
| 298 | assert!(!arena.validate(id)); |
| 299 | assert!(!arena.free(id)); |
| 300 | |
| 301 | // Retired slot is not handed out again; the other slot still works. |
| 302 | let other = arena.allocate(1, 1, 0, 0).unwrap(); |
| 303 | assert_ne!(other.slot, id.slot); |
| 304 | assert!(arena.validate(other)); |
| 305 | assert!(!arena.validate(id)); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn retired_only_slot_exhausts_capacity() { |
| 310 | let mut arena = SequenceArena::with_start_generation(1, u32::MAX); |
| 311 | let id = arena.allocate(1, 1, 0, 0).unwrap(); |
| 312 | assert!(arena.free(id)); |
| 313 | assert!(arena.allocate(1, 1, 0, 0).is_err()); |
| 314 | assert_eq!(arena.active_count(), 0); |
| 315 | } |
| 316 | } |