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-scheduler / 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 | use aien_abi_core::{DecodeObservation, FinishReason, OpEvidence, SamplingParams, SequenceRequest}; |
| 17 | use aien_kv_cache::HOLDER_SLOT; |
| 18 | use aien_platform::{InferenceWork, KvHandle, ModelHandle, Priority, Ticks}; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | use std::collections::HashMap; |
| 21 | use std::sync::Arc; |
| 22 | |
| 23 | /// 64-bit Sequence Identifier composed of a slot index and a generation counter. |
| 24 | /// Layout: [slot: u32 (high 32 bits)][generation: u32 (low 32 bits)] |
| 25 | /// Generation zero is strictly invalid ab initio. |
| 26 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] |
| 27 | pub struct SequenceId { |
| 28 | pub slot: u32, |
| 29 | pub generation: u32, |
| 30 | } |
| 31 | |
| 32 | impl SequenceId { |
| 33 | pub const INVALID: Self = Self { |
| 34 | slot: u32::MAX, |
| 35 | generation: 0, |
| 36 | }; |
| 37 | |
| 38 | pub fn new(slot: u32, generation: u32) -> Result<Self, &'static str> { |
| 39 | if generation == 0 { |
| 40 | return Err("Generation zero is strictly invalid"); |
| 41 | } |
| 42 | Ok(Self { slot, generation }) |
| 43 | } |
| 44 | |
| 45 | #[inline] |
| 46 | pub fn is_valid(&self) -> bool { |
| 47 | self.generation != 0 |
| 48 | } |
| 49 | |
| 50 | #[inline] |
| 51 | pub fn to_u64(&self) -> u64 { |
| 52 | ((self.slot as u64) << 32) | (self.generation as u64) |
| 53 | } |
| 54 | |
| 55 | #[inline] |
| 56 | pub fn from_u64(val: u64) -> Result<Self, &'static str> { |
| 57 | let slot = (val >> 32) as u32; |
| 58 | let generation = (val & 0xFFFF_FFFF) as u32; |
| 59 | if generation == 0 { |
| 60 | return Err("Generation zero is strictly invalid"); |
| 61 | } |
| 62 | Ok(Self { slot, generation }) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl From<SequenceId> for u64 { |
| 67 | fn from(id: SequenceId) -> Self { |
| 68 | id.to_u64() |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | impl TryFrom<u64> for SequenceId { |
| 73 | type Error = &'static str; |
| 74 | fn try_from(val: u64) -> Result<Self, Self::Error> { |
| 75 | SequenceId::from_u64(val) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl std::fmt::Display for SequenceId { |
| 80 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 81 | write!(f, "Seq(slot:{},gen:{})", self.slot, self.generation) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// Immutable, reference-counted prompt token buffer. |
| 86 | /// Guarantees zero allocation overhead across sequence forks and subagent branches. |
| 87 | pub type PromptHandle = Arc<[u32]>; |
| 88 | |
| 89 | /// Opaque identifier for a decoupled completion sink. |
| 90 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 91 | pub struct CompletionSinkId(pub u64); |
| 92 | |
| 93 | /// Structured lifecycle event emitted for a sequence during execution. |
| 94 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 95 | pub enum CompletionEvent { |
| 96 | Token { |
| 97 | seq_id: SequenceId, |
| 98 | token: u32, |
| 99 | }, |
| 100 | Finished { |
| 101 | seq_id: SequenceId, |
| 102 | finish_reason: FinishReason, |
| 103 | total_tokens: usize, |
| 104 | /// How the backend chose this sequence's tokens, taken from the backend |
| 105 | /// when the sequence finished (sc#294). None when the backend does not |
| 106 | /// observe its decoding: an absent claim, not greedy. |
| 107 | #[serde(default)] |
| 108 | decoding: Option<DecodeObservation>, |
| 109 | /// The tensor backend and its op counters (process totals) when the |
| 110 | /// sequence finished (sc#337). None when the backend does not account |
| 111 | /// its ops: an absent claim, not zero fallbacks. |
| 112 | #[serde(default)] |
| 113 | ops: Option<OpEvidence>, |
| 114 | }, |
| 115 | Error { |
| 116 | seq_id: SequenceId, |
| 117 | message: String, |
| 118 | }, |
| 119 | } |
| 120 | |
| 121 | /// Decoupled event consumer trait free from sockets, threads, and processes. |
| 122 | pub trait CompletionSink: Send + Sync { |
| 123 | fn emit(&self, event: CompletionEvent); |
| 124 | } |
| 125 | |
| 126 | /// Channel-based completion sink implementation for async task integration. |
| 127 | pub struct ChannelCompletionSink { |
| 128 | sender: tokio::sync::mpsc::UnboundedSender<CompletionEvent>, |
| 129 | } |
| 130 | |
| 131 | impl ChannelCompletionSink { |
| 132 | pub fn new(sender: tokio::sync::mpsc::UnboundedSender<CompletionEvent>) -> Self { |
| 133 | Self { sender } |
| 134 | } |
| 135 | |
| 136 | pub fn channel() -> (Self, tokio::sync::mpsc::UnboundedReceiver<CompletionEvent>) { |
| 137 | let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); |
| 138 | (Self::new(tx), rx) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | impl CompletionSink for ChannelCompletionSink { |
| 143 | fn emit(&self, event: CompletionEvent) { |
| 144 | let _ = self.sender.send(event); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /// Event router managing active completion sinks. |
| 149 | #[derive(Default)] |
| 150 | pub struct CompletionRouter { |
| 151 | sinks: HashMap<CompletionSinkId, Arc<dyn CompletionSink>>, |
| 152 | next_id: u64, |
| 153 | } |
| 154 | |
| 155 | impl CompletionRouter { |
| 156 | pub fn new() -> Self { |
| 157 | Self { |
| 158 | sinks: HashMap::new(), |
| 159 | next_id: 1, |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | pub fn register(&mut self, sink: Arc<dyn CompletionSink>) -> CompletionSinkId { |
| 164 | let id = CompletionSinkId(self.next_id); |
| 165 | self.next_id += 1; |
| 166 | self.sinks.insert(id, sink); |
| 167 | id |
| 168 | } |
| 169 | |
| 170 | pub fn unregister(&mut self, id: CompletionSinkId) -> Option<Arc<dyn CompletionSink>> { |
| 171 | self.sinks.remove(&id) |
| 172 | } |
| 173 | |
| 174 | pub fn emit(&self, sink_id: CompletionSinkId, event: CompletionEvent) { |
| 175 | if let Some(sink) = self.sinks.get(&sink_id) { |
| 176 | sink.emit(event); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | pub fn broadcast(&self, event: CompletionEvent) { |
| 181 | for sink in self.sinks.values() { |
| 182 | sink.emit(event.clone()); |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// Span of prompt tokens scheduled for prefill execution. |
| 188 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 189 | pub struct PrefillSpan { |
| 190 | pub seq_id: SequenceId, |
| 191 | pub start_pos: usize, |
| 192 | pub length: usize, |
| 193 | } |
| 194 | |
| 195 | /// Single autoregressive decode step scheduled for an active sequence. |
| 196 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 197 | pub struct DecodeItem { |
| 198 | pub seq_id: SequenceId, |
| 199 | pub token_pos: usize, |
| 200 | } |
| 201 | |
| 202 | /// Structured hardware execution plan dividing work into prefill spans and decode steps. |
| 203 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 204 | pub struct BatchPlan { |
| 205 | pub step_id: u64, |
| 206 | pub prefill_spans: Vec<PrefillSpan>, |
| 207 | pub decode_items: Vec<DecodeItem>, |
| 208 | pub total_tokens: usize, |
| 209 | } |
| 210 | |
| 211 | /// Explicit lifecycle phases for a sequence record. |
| 212 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 213 | pub enum SequencePhase { |
| 214 | Waiting, |
| 215 | /// Persistent KV (ADR 0003 section 6.3): queued like `Waiting`, but skipped by |
| 216 | /// admission while a restore of its prefix is in flight. Left by |
| 217 | /// `admit_restored_prefix` (into `Prefill`) or `release_restore` (back to |
| 218 | /// `Waiting`, a plain prefill). |
| 219 | AwaitingRestore, |
| 220 | Prefill, |
| 221 | PrefillInFlight, |
| 222 | Decode, |
| 223 | DecodeInFlight, |
| 224 | Preempted, |
| 225 | Finished, |
| 226 | Cancelled, |
| 227 | } |
| 228 | |
| 229 | /// Authoritative runtime state record for an individual sequence. |
| 230 | #[derive(Debug, Clone)] |
| 231 | pub struct SequenceRecord { |
| 232 | pub seq_id: SequenceId, |
| 233 | pub prompt: PromptHandle, |
| 234 | pub model: ModelHandle, |
| 235 | pub kv: KvHandle, |
| 236 | pub priority: Priority, |
| 237 | pub deadline: Option<Ticks>, |
| 238 | pub branch_parent: Option<SequenceId>, |
| 239 | pub next_token_budget: u32, |
| 240 | pub phase: SequencePhase, |
| 241 | pub tokens_generated: usize, |
| 242 | pub prompt_tokens_prefilled: usize, |
| 243 | pub is_prefilled: bool, |
| 244 | pub sink_id: Option<CompletionSinkId>, |
| 245 | pub sampling_params: SamplingParams, |
| 246 | pub arrival_time_ns: u64, |
| 247 | pub generated_tokens: Vec<u32>, |
| 248 | } |
| 249 | |
| 250 | impl SequenceRecord { |
| 251 | pub fn new( |
| 252 | seq_id: SequenceId, |
| 253 | prompt: PromptHandle, |
| 254 | model: ModelHandle, |
| 255 | kv: KvHandle, |
| 256 | priority: Priority, |
| 257 | deadline: Option<Ticks>, |
| 258 | branch_parent: Option<SequenceId>, |
| 259 | next_token_budget: u32, |
| 260 | sampling_params: SamplingParams, |
| 261 | sink_id: Option<CompletionSinkId>, |
| 262 | ) -> Self { |
| 263 | Self { |
| 264 | seq_id, |
| 265 | prompt, |
| 266 | model, |
| 267 | kv, |
| 268 | priority, |
| 269 | deadline, |
| 270 | branch_parent, |
| 271 | next_token_budget, |
| 272 | phase: SequencePhase::Waiting, |
| 273 | tokens_generated: 0, |
| 274 | prompt_tokens_prefilled: 0, |
| 275 | is_prefilled: false, |
| 276 | sink_id, |
| 277 | sampling_params, |
| 278 | arrival_time_ns: 0, |
| 279 | generated_tokens: Vec::new(), |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | pub fn from_work( |
| 284 | work: InferenceWork, |
| 285 | seq_id: SequenceId, |
| 286 | prompt: PromptHandle, |
| 287 | sampling_params: SamplingParams, |
| 288 | sink_id: Option<CompletionSinkId>, |
| 289 | ) -> Self { |
| 290 | Self { |
| 291 | seq_id, |
| 292 | prompt, |
| 293 | model: work.model, |
| 294 | kv: work.kv, |
| 295 | priority: work.priority, |
| 296 | deadline: work.deadline, |
| 297 | branch_parent: work |
| 298 | .branch_parent |
| 299 | .and_then(|p| SequenceId::from_u64(p).ok()), |
| 300 | next_token_budget: work.next_token_budget, |
| 301 | phase: SequencePhase::Waiting, |
| 302 | tokens_generated: 0, |
| 303 | prompt_tokens_prefilled: 0, |
| 304 | is_prefilled: false, |
| 305 | sink_id, |
| 306 | sampling_params, |
| 307 | arrival_time_ns: 0, |
| 308 | generated_tokens: Vec::new(), |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /// Tokens a prefill of this sequence must compute: the prompt, then every |
| 313 | /// token generated before a preemption (or a prefill-gate refusal) dropped |
| 314 | /// its K/V. A fresh request has no generated tokens, so this is the prompt. |
| 315 | /// A resumed sequence is prefilled through its newest generated token, so |
| 316 | /// the sample after the last chunk is the next new token and no token is |
| 317 | /// emitted twice. |
| 318 | pub fn prefill_input(&self) -> Vec<u32> { |
| 319 | let mut input = Vec::with_capacity(self.prefill_input_len()); |
| 320 | input.extend_from_slice(&self.prompt); |
| 321 | input.extend_from_slice(&self.generated_tokens); |
| 322 | input |
| 323 | } |
| 324 | |
| 325 | /// Length of [`Self::prefill_input`] without building it. |
| 326 | pub fn prefill_input_len(&self) -> usize { |
| 327 | self.prompt.len() + self.generated_tokens.len() |
| 328 | } |
| 329 | |
| 330 | pub fn remaining_prefill_tokens(&self) -> usize { |
| 331 | self.prefill_input_len() |
| 332 | .saturating_sub(self.prompt_tokens_prefilled) |
| 333 | } |
| 334 | |
| 335 | pub fn total_tokens(&self) -> usize { |
| 336 | self.prompt.len() + self.tokens_generated |
| 337 | } |
| 338 | |
| 339 | pub fn is_finished(&self) -> bool { |
| 340 | self.phase == SequencePhase::Finished |
| 341 | || self.tokens_generated >= self.sampling_params.max_tokens |
| 342 | || (self.next_token_budget > 0 |
| 343 | && self.tokens_generated >= self.next_token_budget as usize) |
| 344 | } |
| 345 | |
| 346 | pub fn to_request(&self) -> SequenceRequest { |
| 347 | SequenceRequest { |
| 348 | request_id: self.seq_id.to_u64(), |
| 349 | prompt_tokens: self.prompt.to_vec(), |
| 350 | sampling_params: self.sampling_params.clone(), |
| 351 | arrival_time_ns: self.arrival_time_ns, |
| 352 | priority: self.priority as u8, |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | /// Slot entry within SequenceArena. |
| 358 | #[derive(Debug, Clone)] |
| 359 | pub struct SlotEntry { |
| 360 | pub generation: u32, |
| 361 | pub retired: bool, |
| 362 | pub record: Option<SequenceRecord>, |
| 363 | } |
| 364 | |
| 365 | /// Index for the next new arena slot when `len` slots exist. Slot `u32::MAX` |
| 366 | /// belongs to storage holders (`aien_kv_cache::HOLDER_SLOT`, ADR 0003 section |
| 367 | /// 5.2), so the arena refuses to grow into it and the reservation is a rule, |
| 368 | /// not an assumption about how many sequences a process will ever create. |
| 369 | pub(crate) fn next_slot_index(len: usize) -> Result<u32, String> { |
| 370 | match u32::try_from(len) { |
| 371 | Ok(idx) if idx < HOLDER_SLOT => Ok(idx), |
| 372 | _ => Err(format!( |
| 373 | "sequence arena is full: slot {HOLDER_SLOT} is reserved for storage holders" |
| 374 | )), |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | /// Central state arena managing active sequence records with slot/generation tracking. |
| 379 | #[derive(Debug, Default)] |
| 380 | pub struct SequenceArena { |
| 381 | slots: Vec<SlotEntry>, |
| 382 | free_slots: Vec<u32>, |
| 383 | retired_slots_count: usize, |
| 384 | total_tokens_generated: usize, |
| 385 | total_prefilled_tokens: usize, |
| 386 | } |
| 387 | |
| 388 | impl SequenceArena { |
| 389 | pub fn new() -> Self { |
| 390 | Self { |
| 391 | slots: Vec::new(), |
| 392 | free_slots: Vec::new(), |
| 393 | retired_slots_count: 0, |
| 394 | total_tokens_generated: 0, |
| 395 | total_prefilled_tokens: 0, |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | pub fn with_capacity(capacity: usize) -> Self { |
| 400 | let mut slots = Vec::with_capacity(capacity); |
| 401 | let mut free_slots = Vec::with_capacity(capacity); |
| 402 | for i in 0..capacity { |
| 403 | slots.push(SlotEntry { |
| 404 | generation: 1, // Generation 0 is strictly invalid |
| 405 | retired: false, |
| 406 | record: None, |
| 407 | }); |
| 408 | free_slots.push(i as u32); |
| 409 | } |
| 410 | free_slots.reverse(); |
| 411 | |
| 412 | Self { |
| 413 | slots, |
| 414 | free_slots, |
| 415 | retired_slots_count: 0, |
| 416 | total_tokens_generated: 0, |
| 417 | total_prefilled_tokens: 0, |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | /// Test-only: start every slot at `generation` so the u32::MAX boundary is reachable. |
| 422 | #[cfg(test)] |
| 423 | pub(crate) fn with_start_generation(capacity: usize, generation: u32) -> Self { |
| 424 | let mut arena = Self::with_capacity(capacity); |
| 425 | for slot in &mut arena.slots { |
| 426 | slot.generation = generation; |
| 427 | } |
| 428 | arena |
| 429 | } |
| 430 | |
| 431 | /// Allocates an active sequence slot with a non-zero generation. |
| 432 | /// Retires slot if generation wraps to u32::MAX. |
| 433 | pub fn allocate_slot(&mut self) -> Result<SequenceId, String> { |
| 434 | while let Some(slot_idx) = self.free_slots.pop() { |
| 435 | let slot = &mut self.slots[slot_idx as usize]; |
| 436 | if slot.retired { |
| 437 | continue; |
| 438 | } |
| 439 | if slot.generation == 0 { |
| 440 | slot.generation = 1; |
| 441 | } |
| 442 | return Ok(SequenceId { |
| 443 | slot: slot_idx, |
| 444 | generation: slot.generation, |
| 445 | }); |
| 446 | } |
| 447 | |
| 448 | let slot_idx = next_slot_index(self.slots.len())?; |
| 449 | let generation = 1; // Generation 0 is invalid |
| 450 | self.slots.push(SlotEntry { |
| 451 | generation, |
| 452 | retired: false, |
| 453 | record: None, |
| 454 | }); |
| 455 | |
| 456 | Ok(SequenceId { |
| 457 | slot: slot_idx, |
| 458 | generation, |
| 459 | }) |
| 460 | } |
| 461 | |
| 462 | /// Inserts a sequence into an allocated slot. |
| 463 | pub fn insert_with( |
| 464 | &mut self, |
| 465 | prompt: PromptHandle, |
| 466 | model: ModelHandle, |
| 467 | kv: KvHandle, |
| 468 | priority: Priority, |
| 469 | deadline: Option<Ticks>, |
| 470 | branch_parent: Option<SequenceId>, |
| 471 | next_token_budget: u32, |
| 472 | sampling_params: SamplingParams, |
| 473 | sink_id: Option<CompletionSinkId>, |
| 474 | ) -> Result<SequenceId, String> { |
| 475 | let seq_id = self.allocate_slot()?; |
| 476 | let record = SequenceRecord::new( |
| 477 | seq_id, |
| 478 | prompt, |
| 479 | model, |
| 480 | kv, |
| 481 | priority, |
| 482 | deadline, |
| 483 | branch_parent, |
| 484 | next_token_budget, |
| 485 | sampling_params, |
| 486 | sink_id, |
| 487 | ); |
| 488 | self.slots[seq_id.slot as usize].record = Some(record); |
| 489 | Ok(seq_id) |
| 490 | } |
| 491 | |
| 492 | /// Inserts a sequence record with an explicit SequenceId (e.g. from upstream caller/runtime). |
| 493 | /// Grows the arena to fit the requested slot: a fresh arena has no slots, |
| 494 | /// and refusing explicit ids forces auto allocation whose slot numbering |
| 495 | /// silently diverges from the caller's ids. |
| 496 | pub fn insert_with_id( |
| 497 | &mut self, |
| 498 | seq_id: SequenceId, |
| 499 | prompt: PromptHandle, |
| 500 | model: ModelHandle, |
| 501 | kv: KvHandle, |
| 502 | priority: Priority, |
| 503 | deadline: Option<Ticks>, |
| 504 | branch_parent: Option<SequenceId>, |
| 505 | next_token_budget: u32, |
| 506 | sampling_params: SamplingParams, |
| 507 | sink_id: Option<CompletionSinkId>, |
| 508 | ) -> Result<SequenceId, String> { |
| 509 | let slot_idx = seq_id.slot; |
| 510 | if seq_id.generation == 0 { |
| 511 | return Err("Generation zero is strictly invalid".to_string()); |
| 512 | } |
| 513 | // Checked before the arena grows to fit: slot `u32::MAX` is the storage |
| 514 | // holder slot, and growing towards it would allocate billions of entries. |
| 515 | if slot_idx == HOLDER_SLOT { |
| 516 | return Err(format!( |
| 517 | "slot {slot_idx} is reserved for storage holders and cannot hold a sequence" |
| 518 | )); |
| 519 | } |
| 520 | while (slot_idx as usize) >= self.slots.len() { |
| 521 | let next = self.slots.len() as u32; |
| 522 | self.slots.push(SlotEntry { |
| 523 | generation: 1, |
| 524 | retired: false, |
| 525 | record: None, |
| 526 | }); |
| 527 | self.free_slots.push(next); |
| 528 | } |
| 529 | if let Some(pos) = self.free_slots.iter().position(|&s| s == slot_idx) { |
| 530 | self.free_slots.remove(pos); |
| 531 | } |
| 532 | let slot = &mut self.slots[slot_idx as usize]; |
| 533 | slot.generation = seq_id.generation; |
| 534 | slot.retired = false; |
| 535 | let record = SequenceRecord::new( |
| 536 | seq_id, |
| 537 | prompt, |
| 538 | model, |
| 539 | kv, |
| 540 | priority, |
| 541 | deadline, |
| 542 | branch_parent, |
| 543 | next_token_budget, |
| 544 | sampling_params, |
| 545 | sink_id, |
| 546 | ); |
| 547 | slot.record = Some(record); |
| 548 | Ok(seq_id) |
| 549 | } |
| 550 | |
| 551 | /// Validates whether a SequenceId is stale: |
| 552 | /// - generation 0 |
| 553 | /// - slot index out of bounds |
| 554 | /// - generation doesn't match current slot generation |
| 555 | /// - slot has no active record |
| 556 | pub fn is_stale(&self, id: SequenceId) -> bool { |
| 557 | if id.generation == 0 || (id.slot as usize) >= self.slots.len() { |
| 558 | return true; |
| 559 | } |
| 560 | let slot = &self.slots[id.slot as usize]; |
| 561 | slot.generation != id.generation || slot.record.is_none() |
| 562 | } |
| 563 | |
| 564 | pub fn get(&self, id: SequenceId) -> Option<&SequenceRecord> { |
| 565 | if id.generation == 0 || (id.slot as usize) >= self.slots.len() { |
| 566 | return None; |
| 567 | } |
| 568 | let slot = &self.slots[id.slot as usize]; |
| 569 | if slot.generation == id.generation { |
| 570 | slot.record.as_ref() |
| 571 | } else { |
| 572 | None |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | pub fn get_mut(&mut self, id: SequenceId) -> Option<&mut SequenceRecord> { |
| 577 | if id.generation == 0 || (id.slot as usize) >= self.slots.len() { |
| 578 | return None; |
| 579 | } |
| 580 | let slot = &mut self.slots[id.slot as usize]; |
| 581 | if slot.generation == id.generation { |
| 582 | slot.record.as_mut() |
| 583 | } else { |
| 584 | None |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | /// Deallocates a sequence, advancing its generation to invalidate stale queued IDs. |
| 589 | /// Retires the slot if generation reaches u32::MAX. |
| 590 | pub fn free_sequence(&mut self, id: SequenceId) -> bool { |
| 591 | if id.generation == 0 || (id.slot as usize) >= self.slots.len() { |
| 592 | return false; |
| 593 | } |
| 594 | let slot = &mut self.slots[id.slot as usize]; |
| 595 | if slot.generation != id.generation || slot.record.is_none() { |
| 596 | return false; |
| 597 | } |
| 598 | |
| 599 | slot.record = None; |
| 600 | if slot.generation == u32::MAX { |
| 601 | slot.retired = true; |
| 602 | self.retired_slots_count += 1; |
| 603 | } else { |
| 604 | slot.generation += 1; |
| 605 | self.free_slots.push(id.slot); |
| 606 | } |
| 607 | true |
| 608 | } |
| 609 | |
| 610 | /// Zero-copy sequence fork preserving immutable PromptHandle. |
| 611 | pub fn fork( |
| 612 | &mut self, |
| 613 | parent_id: SequenceId, |
| 614 | sink_id: Option<CompletionSinkId>, |
| 615 | ) -> Result<SequenceId, String> { |
| 616 | let parent = self |
| 617 | .get(parent_id) |
| 618 | .ok_or_else(|| format!("Parent sequence {} not found in arena or stale", parent_id))? |
| 619 | .clone(); |
| 620 | |
| 621 | let child_id = self.allocate_slot()?; |
| 622 | let child_record = SequenceRecord { |
| 623 | seq_id: child_id, |
| 624 | prompt: Arc::clone(&parent.prompt), |
| 625 | model: parent.model, |
| 626 | kv: KvHandle(child_id.to_u64()), |
| 627 | priority: parent.priority, |
| 628 | deadline: parent.deadline, |
| 629 | branch_parent: Some(parent_id), |
| 630 | next_token_budget: parent.next_token_budget, |
| 631 | phase: SequencePhase::Decode, |
| 632 | tokens_generated: parent.tokens_generated, |
| 633 | prompt_tokens_prefilled: parent.prompt_tokens_prefilled, |
| 634 | is_prefilled: parent.is_prefilled, |
| 635 | sink_id, |
| 636 | sampling_params: parent.sampling_params.clone(), |
| 637 | arrival_time_ns: parent.arrival_time_ns, |
| 638 | generated_tokens: parent.generated_tokens.clone(), |
| 639 | }; |
| 640 | |
| 641 | self.slots[child_id.slot as usize].record = Some(child_record); |
| 642 | Ok(child_id) |
| 643 | } |
| 644 | |
| 645 | pub fn active_ids(&self) -> Vec<SequenceId> { |
| 646 | let mut ids = Vec::new(); |
| 647 | for (idx, slot) in self.slots.iter().enumerate() { |
| 648 | if slot.record.is_some() { |
| 649 | ids.push(SequenceId { |
| 650 | slot: idx as u32, |
| 651 | generation: slot.generation, |
| 652 | }); |
| 653 | } |
| 654 | } |
| 655 | ids |
| 656 | } |
| 657 | |
| 658 | pub fn active_count(&self) -> usize { |
| 659 | self.slots.iter().filter(|s| s.record.is_some()).count() |
| 660 | } |
| 661 | |
| 662 | pub fn len(&self) -> usize { |
| 663 | self.active_count() |
| 664 | } |
| 665 | |
| 666 | pub fn is_empty(&self) -> bool { |
| 667 | self.active_count() == 0 |
| 668 | } |
| 669 | |
| 670 | pub fn retired_slots(&self) -> usize { |
| 671 | self.retired_slots_count |
| 672 | } |
| 673 | |
| 674 | pub fn record_generated_token(&mut self, seq_id: SequenceId, token: u32) { |
| 675 | if let Some(record) = self.get_mut(seq_id) { |
| 676 | record.tokens_generated += 1; |
| 677 | record.generated_tokens.push(token); |
| 678 | self.total_tokens_generated += 1; |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | pub fn record_prefilled_tokens(&mut self, seq_id: SequenceId, count: usize) { |
| 683 | if let Some(record) = self.get_mut(seq_id) { |
| 684 | record.prompt_tokens_prefilled += count; |
| 685 | if record.prompt_tokens_prefilled >= record.prompt.len() { |
| 686 | record.is_prefilled = true; |
| 687 | record.phase = SequencePhase::Decode; |
| 688 | } else { |
| 689 | record.phase = SequencePhase::Prefill; |
| 690 | } |
| 691 | self.total_prefilled_tokens += count; |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | pub fn total_tokens_generated(&self) -> usize { |
| 696 | self.total_tokens_generated |
| 697 | } |
| 698 | |
| 699 | pub fn total_prefilled_tokens(&self) -> usize { |
| 700 | self.total_prefilled_tokens |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | #[cfg(test)] |
| 705 | mod tests { |
| 706 | use super::*; |
| 707 | |
| 708 | #[test] |
| 709 | fn test_sequence_id_generation_zero_invalid() { |
| 710 | assert!(SequenceId::new(0, 0).is_err()); |
| 711 | assert!(!SequenceId::INVALID.is_valid()); |
| 712 | assert!(SequenceId::from_u64(0).is_err()); |
| 713 | |
| 714 | let valid = SequenceId::new(42, 1).unwrap(); |
| 715 | assert!(valid.is_valid()); |
| 716 | let raw = valid.to_u64(); |
| 717 | let recovered = SequenceId::from_u64(raw).unwrap(); |
| 718 | assert_eq!(valid, recovered); |
| 719 | assert_eq!(recovered.slot, 42); |
| 720 | assert_eq!(recovered.generation, 1); |
| 721 | } |
| 722 | |
| 723 | #[test] |
| 724 | fn test_slot_retirement_on_generation_wrap() { |
| 725 | let mut arena = SequenceArena::new(); |
| 726 | let id1 = arena.allocate_slot().unwrap(); |
| 727 | assert_eq!(id1.slot, 0); |
| 728 | assert_eq!(id1.generation, 1); |
| 729 | |
| 730 | // Manually simulate generation approaching u32::MAX |
| 731 | arena.slots[0].generation = u32::MAX; |
| 732 | arena.slots[0].record = Some(SequenceRecord::new( |
| 733 | SequenceId { |
| 734 | slot: 0, |
| 735 | generation: u32::MAX, |
| 736 | }, |
| 737 | Arc::from(vec![1, 2, 3].into_boxed_slice()), |
| 738 | ModelHandle(0), |
| 739 | KvHandle(0), |
| 740 | Priority::Normal, |
| 741 | None, |
| 742 | None, |
| 743 | 10, |
| 744 | SamplingParams::default(), |
| 745 | None, |
| 746 | )); |
| 747 | |
| 748 | // Free the sequence -> should retire slot 0 |
| 749 | let target_id = SequenceId { |
| 750 | slot: 0, |
| 751 | generation: u32::MAX, |
| 752 | }; |
| 753 | assert!(arena.free_sequence(target_id)); |
| 754 | assert_eq!(arena.retired_slots(), 1); |
| 755 | assert!(arena.slots[0].retired); |
| 756 | |
| 757 | // Next allocation should NOT reuse retired slot 0 |
| 758 | let id2 = arena.allocate_slot().unwrap(); |
| 759 | assert_eq!(id2.slot, 1); |
| 760 | assert_eq!(id2.generation, 1); |
| 761 | } |
| 762 | |
| 763 | fn insert_test_seq(arena: &mut SequenceArena) -> SequenceId { |
| 764 | let prompt: PromptHandle = Arc::from(vec![1, 2, 3].into_boxed_slice()); |
| 765 | arena |
| 766 | .insert_with( |
| 767 | prompt, |
| 768 | ModelHandle(0), |
| 769 | KvHandle(0), |
| 770 | Priority::Normal, |
| 771 | None, |
| 772 | None, |
| 773 | 10, |
| 774 | SamplingParams::default(), |
| 775 | None, |
| 776 | ) |
| 777 | .unwrap() |
| 778 | } |
| 779 | |
| 780 | #[test] |
| 781 | fn test_generation_boundary_below_max_reuses_then_retires_at_max() { |
| 782 | let mut arena = SequenceArena::with_start_generation(2, u32::MAX - 1); |
| 783 | let id = insert_test_seq(&mut arena); |
| 784 | assert_eq!(id.generation, u32::MAX - 1); |
| 785 | assert!(arena.free_sequence(id)); |
| 786 | assert_eq!(arena.retired_slots(), 0); |
| 787 | |
| 788 | // Slot is reused at exactly u32::MAX. |
| 789 | let top = insert_test_seq(&mut arena); |
| 790 | assert_eq!(top.slot, id.slot); |
| 791 | assert_eq!(top.generation, u32::MAX); |
| 792 | assert!(arena.get(id).is_none()); |
| 793 | |
| 794 | // Freeing at u32::MAX retires; neither stale id resolves, none is reallocated. |
| 795 | assert!(arena.free_sequence(top)); |
| 796 | assert_eq!(arena.retired_slots(), 1); |
| 797 | assert!(arena.get(top).is_none()); |
| 798 | assert!(!arena.free_sequence(top)); |
| 799 | let next = insert_test_seq(&mut arena); |
| 800 | assert_ne!(next.slot, top.slot); |
| 801 | } |
| 802 | |
| 803 | #[test] |
| 804 | fn test_stale_work_rejection() { |
| 805 | let mut arena = SequenceArena::new(); |
| 806 | let prompt: PromptHandle = Arc::from(vec![10, 20, 30].into_boxed_slice()); |
| 807 | let id1 = arena |
| 808 | .insert_with( |
| 809 | prompt, |
| 810 | ModelHandle(0), |
| 811 | KvHandle(0), |
| 812 | Priority::Normal, |
| 813 | None, |
| 814 | None, |
| 815 | 10, |
| 816 | SamplingParams::default(), |
| 817 | None, |
| 818 | ) |
| 819 | .unwrap(); |
| 820 | |
| 821 | assert!(!arena.is_stale(id1)); |
| 822 | |
| 823 | // Free sequence 1 -> generation bumps to 2 |
| 824 | assert!(arena.free_sequence(id1)); |
| 825 | |
| 826 | // Old id1 is now stale! |
| 827 | assert!(arena.is_stale(id1)); |
| 828 | assert!(arena.get(id1).is_none()); |
| 829 | |
| 830 | // New allocation in slot 0 gets generation 2 |
| 831 | let prompt2: PromptHandle = Arc::from(vec![40, 50].into_boxed_slice()); |
| 832 | let id2 = arena |
| 833 | .insert_with( |
| 834 | prompt2, |
| 835 | ModelHandle(0), |
| 836 | KvHandle(0), |
| 837 | Priority::Normal, |
| 838 | None, |
| 839 | None, |
| 840 | 10, |
| 841 | SamplingParams::default(), |
| 842 | None, |
| 843 | ) |
| 844 | .unwrap(); |
| 845 | |
| 846 | assert_eq!(id2.slot, id1.slot); |
| 847 | assert_eq!(id2.generation, id1.generation + 1); |
| 848 | assert!(!arena.is_stale(id2)); |
| 849 | assert!(arena.is_stale(id1)); // id1 still stale! |
| 850 | } |
| 851 | |
| 852 | #[test] |
| 853 | fn test_prompt_handle_sharing_and_zero_copy_fork() { |
| 854 | let prompt_tokens = vec![1, 2, 3, 4, 5]; |
| 855 | let handle: PromptHandle = Arc::from(prompt_tokens.into_boxed_slice()); |
| 856 | |
| 857 | let mut arena = SequenceArena::new(); |
| 858 | let parent_id = arena |
| 859 | .insert_with( |
| 860 | handle.clone(), |
| 861 | ModelHandle(0), |
| 862 | KvHandle(1), |
| 863 | Priority::Normal, |
| 864 | None, |
| 865 | None, |
| 866 | 128, |
| 867 | SamplingParams::default(), |
| 868 | None, |
| 869 | ) |
| 870 | .unwrap(); |
| 871 | |
| 872 | assert_eq!(arena.active_count(), 1); |
| 873 | |
| 874 | let child_id = arena.fork(parent_id, None).unwrap(); |
| 875 | assert_eq!(arena.active_count(), 2); |
| 876 | |
| 877 | let child = arena.get(child_id).unwrap(); |
| 878 | assert_eq!(child.branch_parent, Some(parent_id)); |
| 879 | assert!(Arc::ptr_eq(&child.prompt, &handle)); |
| 880 | } |
| 881 | |
| 882 | #[test] |
| 883 | fn explicit_ids_in_the_holder_slot_are_refused_without_growing_the_arena() { |
| 884 | let mut arena = SequenceArena::new(); |
| 885 | let holder_shaped = SequenceId::new(HOLDER_SLOT, 3).unwrap(); |
| 886 | let handle: PromptHandle = Arc::from(vec![1u32, 2].into_boxed_slice()); |
| 887 | let err = arena |
| 888 | .insert_with_id( |
| 889 | holder_shaped, |
| 890 | handle, |
| 891 | ModelHandle(0), |
| 892 | KvHandle(0), |
| 893 | Priority::Normal, |
| 894 | None, |
| 895 | None, |
| 896 | 1, |
| 897 | SamplingParams::default(), |
| 898 | None, |
| 899 | ) |
| 900 | .unwrap_err(); |
| 901 | assert!(err.contains("reserved for storage holders"), "{err}"); |
| 902 | assert_eq!(arena.active_count(), 0); |
| 903 | assert!(arena.is_stale(holder_shaped)); |
| 904 | } |
| 905 | |
| 906 | #[test] |
| 907 | fn next_slot_index_stops_below_the_holder_slot() { |
| 908 | // Slot u32::MAX is reserved for storage holders (ADR 0003 section 5.2). |
| 909 | assert_eq!(next_slot_index(0), Ok(0)); |
| 910 | assert_eq!(next_slot_index(u32::MAX as usize - 1), Ok(u32::MAX - 1)); |
| 911 | assert!(next_slot_index(u32::MAX as usize).is_err()); |
| 912 | assert!(next_slot_index(u32::MAX as usize + 1).is_err()); |
| 913 | } |
| 914 | |
| 915 | #[test] |
| 916 | fn test_completion_router_registration_and_dispatch() { |
| 917 | let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); |
| 918 | let sink = Arc::new(ChannelCompletionSink::new(tx)); |
| 919 | |
| 920 | let mut router = CompletionRouter::new(); |
| 921 | let sink_id = router.register(sink); |
| 922 | |
| 923 | let seq_id = SequenceId::new(1, 1).unwrap(); |
| 924 | router.emit(sink_id, CompletionEvent::Token { seq_id, token: 42 }); |
| 925 | |
| 926 | let event = rx.try_recv().unwrap(); |
| 927 | match event { |
| 928 | CompletionEvent::Token { seq_id: id, token } => { |
| 929 | assert_eq!(id, seq_id); |
| 930 | assert_eq!(token, 42); |
| 931 | } |
| 932 | _ => panic!("Unexpected event"), |
| 933 | } |
| 934 | } |
| 935 | } |