Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-scheduler/src/lib.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-scheduler / src / lib.rs` 1813 lines ยท 76775 bytes Raw Blame History 1 #![allow(clippy::too_many_arguments)] 2 // SPDX-License-Identifier: Apache-2.0 3 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 pub mod dual_observer; 18 pub mod sequence; 19 20 pub use sequence::*; 21 22 use crate::dual_observer::{ 23 AdmissionCandidate, AdmissionVerdict, AdmitPreemptAlternatives, AdmitPreemptChoice, 24 AdmitPreemptRecord, AdmitPreemptTrace, BatchLimits, BatchOutcome, DecisionObserver, KvReading, 25 LoopStop, PreemptionVictim, RunningItem, RunningVerdict, SERVE_ADMIT_PREEMPT_SITE, 26 }; 27 use aien_abi_core::{ 28 AienInferenceBackend, DecodeOutput, FinishReason, ScheduledBatch, SequenceRequest, StepMetrics, 29 }; 30 use aien_inference_abi::KV_POOL_EXHAUSTED_PREFIX; 31 use aien_kv_cache::{AienKvManager, PrefillGateError, PrefillState}; 32 use aien_platform::{InferenceWork, Priority}; 33 use parking_lot::RwLock; 34 use serde::{Deserialize, Serialize}; 35 use std::collections::{HashMap, VecDeque}; 36 use std::sync::Arc; 37 use std::time::Instant; 38 39 /// Prefill readiness gate (PREFILL-GATE). A sequence may enter decode only 40 /// when its block table K/V was computed by a completed prefill 41 /// (`BlockTable::is_prefill_ready`). Having a block table is not enough: 42 /// `allocate_sequence` only reserves and zeroes blocks. 43 #[inline] 44 fn prefill_gate_allows_decode(table_ready: bool) -> bool { 45 if cfg!(feature = "prefill_mutant_no_check") { 46 // MUTANT: readiness check removed. Tests must catch this. 47 return true; 48 } 49 table_ready 50 } 51 52 #[derive(Debug, Clone, Serialize, Deserialize)] 53 pub struct SchedulerConfig { 54 pub max_batch_size: usize, 55 pub max_batch_tokens: usize, 56 pub max_prefill_tokens: usize, 57 pub prefill_chunk_size: usize, 58 pub chunk_prefill: bool, 59 pub watermark_blocks: usize, 60 } 61 62 impl Default for SchedulerConfig { 63 fn default() -> Self { 64 Self { 65 max_batch_size: 64, 66 max_batch_tokens: 4096, 67 max_prefill_tokens: 2048, 68 prefill_chunk_size: 512, 69 chunk_prefill: true, 70 watermark_blocks: 4, 71 } 72 } 73 } 74 75 #[derive(Debug, Clone, Default)] 76 pub struct SchedulerMetrics { 77 pub total_steps: u64, 78 pub admitted_requests: u64, 79 pub finished_requests: u64, 80 pub preempted_requests: u64, 81 pub total_prefill_tokens: u64, 82 pub total_decode_tokens: u64, 83 pub avg_step_latency_us: f64, 84 pub chunked_prefill_steps: u64, 85 /// Finish hooks that returned an error (persistent KV, ADR 0003 section 6.1). 86 /// The sequence is freed regardless. 87 pub finish_hook_failures: u64, 88 } 89 90 /// What a [`FinishHook`] is told about the request that is finishing. 91 #[derive(Debug)] 92 pub struct FinishContext<'a> { 93 pub seq_id: SequenceId, 94 /// `seq_id` as the u64 the KV manager and the backend know it by. It carries 95 /// the arena generation, so it is the incarnation of this request. 96 pub request_id: u64, 97 pub reason: FinishReason, 98 /// The tokens whose K/V is written, in order, without the last token (which 99 /// has none). Taken from the backend when it answers (it knows what is in the 100 /// pool); otherwise, for a backend that does not manage the KV cache itself, 101 /// derived from the scheduler's own record (`AienScheduler::computed_prefix`). 102 /// `None` when nobody can say, in which case nothing may be parked. 103 pub computed_prefix: Option>, 104 pub prompt: &'a [u32], 105 } 106 107 /// Persistent KV (ADR 0003 section 6.1, review finding 2). Runs inside the 108 /// scheduler's finish transaction, under the KV write guard it already takes for 109 /// `free_sequence`, and BEFORE that free, so the sequence's blocks have a 110 /// reference at every instant. Typical use: `fork_range` into storage holders 111 /// and push an intent to a lock-free outbox. The hook must not block, do I/O or 112 /// take any other lock held across an await. It is not run for a `Preempted` 113 /// finish (its K/V is incomplete) and not for an id the arena no longer knows. 114 /// An `Err` is counted (`SchedulerMetrics::finish_hook_failures`) and the 115 /// sequence is freed anyway; undoing a partial fork is the hook's own business 116 /// (DOCS SILENT; the narrowest rule is that the scheduler never retries or 117 /// rolls back for it). A panic is not caught. 118 pub trait FinishHook: Send + Sync { 119 fn on_finish(&self, kv: &mut AienKvManager, ctx: &FinishContext<'_>) -> Result<(), String>; 120 } 121 122 /// Native continuous batching LLM scheduler managing SequenceArena, 123 /// decoupled CompletionRouter, and zero-token-clone queues. 124 pub struct AienScheduler { 125 config: SchedulerConfig, 126 kv_manager: Arc>, 127 arena: SequenceArena, 128 completion_router: CompletionRouter, 129 waiting_queue: VecDeque, 130 preempted_queue: VecDeque, 131 /// Sequences whose K/V this scheduler freed while they stay live (watermark 132 /// preemption, a failed append, a prefill-gate refusal). The backend still 133 /// holds their per-sequence state (positions, dense caches, a held sample), 134 /// which would make the re-prefill start at a stale position. `step` drops 135 /// that state through `release_sequence` before the next `execute_step`. 136 pending_backend_releases: Vec, 137 running_sequences: Vec, 138 step_id: u64, 139 metrics: SchedulerMetrics, 140 /// DUAL `serve.admit_preempt` read-only tap. `None` (the default) skips 141 /// every tracing branch in `build_scheduled_batch`. 142 observer: Option>, 143 /// Persistent KV finish hook. `None` (the default) is today's behaviour exactly. 144 finish_hook: Option>, 145 } 146 147 impl AienScheduler { 148 pub fn new(config: SchedulerConfig, kv_manager: Arc>) -> Self { 149 Self { 150 config, 151 kv_manager, 152 arena: SequenceArena::new(), 153 completion_router: CompletionRouter::new(), 154 waiting_queue: VecDeque::new(), 155 preempted_queue: VecDeque::new(), 156 pending_backend_releases: Vec::new(), 157 running_sequences: Vec::new(), 158 step_id: 0, 159 metrics: SchedulerMetrics::default(), 160 observer: None, 161 finish_hook: None, 162 } 163 } 164 165 /// Installs (or with `None` removes) the finish hook (see [`FinishHook`]). 166 pub fn set_finish_hook(&mut self, hook: Option>) { 167 self.finish_hook = hook; 168 } 169 170 pub fn finish_hook_installed(&self) -> bool { 171 self.finish_hook.is_some() 172 } 173 174 /// Installs (or with `None` removes) the DUAL `serve.admit_preempt` 175 /// observer. The observer is shown each decision after it is final and 176 /// cannot change it (see `dual_observer`). 177 pub fn set_decision_observer(&mut self, observer: Option>) { 178 self.observer = observer; 179 } 180 181 pub fn decision_observer_installed(&self) -> bool { 182 self.observer.is_some() 183 } 184 185 pub fn config(&self) -> &SchedulerConfig { 186 &self.config 187 } 188 189 pub fn metrics(&self) -> &SchedulerMetrics { 190 &self.metrics 191 } 192 193 pub fn arena(&self) -> &SequenceArena { 194 &self.arena 195 } 196 197 pub fn arena_mut(&mut self) -> &mut SequenceArena { 198 &mut self.arena 199 } 200 201 pub fn completion_router(&self) -> &CompletionRouter { 202 &self.completion_router 203 } 204 205 pub fn completion_router_mut(&mut self) -> &mut CompletionRouter { 206 &mut self.completion_router 207 } 208 209 pub fn register_completion_sink(&mut self, sink: Arc) -> CompletionSinkId { 210 self.completion_router.register(sink) 211 } 212 213 pub fn waiting_count(&self) -> usize { 214 self.waiting_queue.len() 215 } 216 217 pub fn preempted_count(&self) -> usize { 218 self.preempted_queue.len() 219 } 220 221 /// Takes the ids whose backend per-sequence state must be dropped through 222 /// `AienInferenceBackend::release_sequence` before the next `execute_step` 223 /// (see `pending_backend_releases`). `step` does this itself; a driver that 224 /// executes `build_scheduled_batch` or `build_batch_plan` on its own must 225 /// call it and release each id, or a resumed sequence computes at stale 226 /// positions. 227 pub fn take_pending_backend_releases(&mut self) -> Vec { 228 std::mem::take(&mut self.pending_backend_releases) 229 } 230 231 pub fn running_count(&self) -> usize { 232 self.running_sequences.len() 233 } 234 235 /// Submits a SequenceRequest, creating an immutable PromptHandle and allocating a SequenceId. 236 pub fn submit_request(&mut self, request: SequenceRequest) -> SequenceId { 237 let prompt_slice: Box<[u32]> = request.prompt_tokens.into_boxed_slice(); 238 let prompt_handle: PromptHandle = Arc::from(prompt_slice); 239 let priority = match request.priority { 240 0 => Priority::Background, 241 1 => Priority::Normal, 242 2 => Priority::Interactive, 243 _ => Priority::Realtime, 244 }; 245 246 let seq_id = if request.request_id != 0 && (request.request_id >> 32) > 0 { 247 if let Ok(explicit_id) = SequenceId::from_u64(request.request_id) { 248 self.arena 249 .insert_with_id( 250 explicit_id, 251 prompt_handle.clone(), 252 aien_platform::ModelHandle(0), 253 aien_platform::KvHandle(0), 254 priority, 255 None, 256 None, 257 request.sampling_params.max_tokens as u32, 258 request.sampling_params.clone(), 259 None, 260 ) 261 .unwrap_or_else(|_| { 262 self.arena 263 .insert_with( 264 prompt_handle, 265 aien_platform::ModelHandle(0), 266 aien_platform::KvHandle(0), 267 priority, 268 None, 269 None, 270 request.sampling_params.max_tokens as u32, 271 request.sampling_params, 272 None, 273 ) 274 .expect("Arena allocation failed") 275 }) 276 } else { 277 self.arena 278 .insert_with( 279 prompt_handle, 280 aien_platform::ModelHandle(0), 281 aien_platform::KvHandle(0), 282 priority, 283 None, 284 None, 285 request.sampling_params.max_tokens as u32, 286 request.sampling_params, 287 None, 288 ) 289 .expect("Arena allocation failed") 290 } 291 } else { 292 self.arena 293 .insert_with( 294 prompt_handle, 295 aien_platform::ModelHandle(0), 296 aien_platform::KvHandle(0), 297 priority, 298 None, 299 None, 300 request.sampling_params.max_tokens as u32, 301 request.sampling_params, 302 None, 303 ) 304 .expect("Arena allocation failed") 305 }; 306 307 self.waiting_queue.push_back(seq_id); 308 self.metrics.admitted_requests += 1; 309 seq_id 310 } 311 312 /// Submits structured platform InferenceWork without cloning prompt tokens. 313 pub fn submit_work( 314 &mut self, 315 work: InferenceWork, 316 prompt: PromptHandle, 317 sampling_params: Option, 318 sink_id: Option, 319 ) -> Result { 320 let sampling = sampling_params.unwrap_or_default(); 321 let seq_id = self.arena.insert_with( 322 prompt, 323 work.model, 324 work.kv, 325 work.priority, 326 work.deadline, 327 work.branch_parent 328 .and_then(|p| SequenceId::from_u64(p).ok()), 329 work.next_token_budget, 330 sampling, 331 sink_id, 332 )?; 333 334 self.waiting_queue.push_back(seq_id); 335 self.metrics.admitted_requests += 1; 336 Ok(seq_id) 337 } 338 339 /// Zero-copy sequence fork preserving immutable PromptHandle. 340 pub fn fork_sequence( 341 &mut self, 342 parent_id: SequenceId, 343 sink_id: Option, 344 ) -> Result { 345 if self.arena.is_stale(parent_id) { 346 return Err(format!( 347 "Parent sequence {} is stale or inactive", 348 parent_id 349 )); 350 } 351 352 let child_id = self.arena.fork(parent_id, sink_id)?; 353 354 // Fork block table in KV manager 355 { 356 let mut kv = self.kv_manager.write(); 357 kv.fork_sequence(parent_id.to_u64(), child_id.to_u64())?; 358 } 359 360 self.running_sequences.push(child_id); 361 Ok(child_id) 362 } 363 364 /// Legacy backward compatibility for fork_subagent(parent_id, child_id). 365 pub fn fork_subagent(&mut self, parent_raw: u64, child_raw: u64) -> Result<(), String> { 366 self.fork_subagent_with_sink(parent_raw, child_raw, None) 367 } 368 369 /// Subagent fork with completion sink routing for streamed output. 370 pub fn fork_subagent_with_sink( 371 &mut self, 372 parent_raw: u64, 373 child_raw: u64, 374 sink_id: Option, 375 ) -> Result<(), String> { 376 self.fork_subagent_with_sink_ids(parent_raw, child_raw, sink_id) 377 .map(|_| ()) 378 } 379 380 /// Same as `fork_subagent_with_sink`, returning the (parent, child) KV 381 /// sequence ids the fork was recorded under, so the runtime can fork the 382 /// backend's per-sequence state under the same ids (PREFILL-E2E C4). 383 pub fn fork_subagent_with_sink_ids( 384 &mut self, 385 parent_raw: u64, 386 child_raw: u64, 387 sink_id: Option, 388 ) -> Result<(u64, u64), String> { 389 let parent_id = self 390 .running_sequences 391 .iter() 392 .copied() 393 .find(|id| id.to_u64() == parent_raw || id.slot as u64 == parent_raw) 394 .or_else(|| SequenceId::from_u64(parent_raw).ok()) 395 .ok_or_else(|| format!("Parent sequence {} not found in running pool", parent_raw))?; 396 397 if self.arena.is_stale(parent_id) { 398 return Err(format!("Parent sequence {} is stale", parent_id)); 399 } 400 401 let child_id = self.arena.fork(parent_id, sink_id)?; 402 403 let kv_ids = { 404 let mut kv = self.kv_manager.write(); 405 match kv.fork_sequence(parent_id.to_u64(), child_id.to_u64()) { 406 Ok(_) => (parent_id.to_u64(), child_id.to_u64()), 407 Err(_) => { 408 kv.fork_sequence(parent_raw, child_raw)?; 409 (parent_raw, child_raw) 410 } 411 } 412 }; 413 414 self.running_sequences.push(child_id); 415 Ok(kv_ids) 416 } 417 418 /// Tokens of `seq_id` whose K/V is written, derived from the scheduler's own 419 /// record: the prompt plus every generated token except the last (ADR 0003 420 /// section 6.2, review finding 3). A decode step feeds the previous token 421 /// through the model and samples a new one, so the newest token has no K/V; 422 /// after prefill the first sampled token is likewise pending. `None` for an 423 /// id this arena does not know (another incarnation) or a sequence that has 424 /// not finished its prefill and produced a token. This is the scheduler's 425 /// bookkeeping, not proof the bytes are in the pool: a backend that keeps its 426 /// own K/V answers through `AienInferenceBackend::computed_prefix` instead. 427 pub fn computed_prefix(&self, seq_id: SequenceId) -> Option> { 428 let rec = self.arena.get(seq_id)?; 429 let (_newest, computed) = rec.generated_tokens.split_last()?; 430 if !rec.is_prefilled { 431 return None; 432 } 433 let mut prefix = Vec::with_capacity(rec.prompt.len() + computed.len()); 434 prefix.extend_from_slice(&rec.prompt); 435 prefix.extend_from_slice(computed); 436 Some(prefix) 437 } 438 439 /// The finish transaction (ADR 0003 section 6.1): in one KV write guard, 440 /// run the finish hook (if any), then `free_sequence`. The backend is asked 441 /// for the computed prefix first, before the guard, and is not touched under 442 /// it. With no hook this is exactly `free_sequence` under the write guard. 443 fn finish_kv_transaction( 444 &mut self, 445 backend: &(dyn AienInferenceBackend + '_), 446 seq_id: SequenceId, 447 reason: FinishReason, 448 ) { 449 let request_id = seq_id.to_u64(); 450 let hook = match &self.finish_hook { 451 Some(hook) if reason != FinishReason::Preempted && !self.arena.is_stale(seq_id) => { 452 Some(hook.clone()) 453 } 454 _ => None, 455 }; 456 let Some(hook) = hook else { 457 let _ = self.kv_manager.write().free_sequence(request_id); 458 return; 459 }; 460 let computed_prefix = match backend.computed_prefix(request_id) { 461 Some(prefix) => Some(prefix), 462 None if !backend.manages_kv_cache() => self.computed_prefix(seq_id), 463 None => None, 464 }; 465 let prompt = self.arena.get(seq_id).map(|rec| rec.prompt.clone()); 466 let ctx = FinishContext { 467 seq_id, 468 request_id, 469 reason, 470 computed_prefix, 471 prompt: prompt.as_deref().map_or(&[][..], |p| p), 472 }; 473 let mut kv = self.kv_manager.write(); 474 if hook.on_finish(&mut kv, &ctx).is_err() { 475 self.metrics.finish_hook_failures += 1; 476 } 477 let _ = kv.free_sequence(request_id); 478 } 479 480 fn is_awaiting_restore(&self, id: SequenceId) -> bool { 481 self.arena 482 .get(id) 483 .is_some_and(|rec| rec.phase == SequencePhase::AwaitingRestore) 484 } 485 486 /// Persistent KV (ADR 0003 section 6.3): holds a request that is waiting in 487 /// the queue while a restore of its prefix is in flight. It stays in the 488 /// waiting queue in its place, phase `AwaitingRestore`, and admission skips 489 /// it without blocking the requests behind it. Refused (nothing changed) for 490 /// an id this arena no longer knows, or one that is not a plain waiting 491 /// request in the waiting queue. 492 pub fn hold_for_restore(&mut self, seq_id: SequenceId) -> Result<(), String> { 493 let rec = self 494 .arena 495 .get(seq_id) 496 .ok_or_else(|| format!("hold_for_restore: sequence {seq_id} is stale or unknown"))?; 497 if rec.phase != SequencePhase::Waiting || !self.waiting_queue.contains(&seq_id) { 498 return Err(format!( 499 "hold_for_restore: sequence {seq_id} is {:?}, not a waiting request", 500 rec.phase 501 )); 502 } 503 if let Some(rec) = self.arena.get_mut(seq_id) { 504 rec.phase = SequencePhase::AwaitingRestore; 505 } 506 Ok(()) 507 } 508 509 /// Ends a hold without restoring (the restore missed, failed or was 510 /// stale): the request is `Waiting` again, in its original place, and will 511 /// be admitted with a plain prefill from zero. Refused for an id that is 512 /// stale or not held. 513 pub fn release_restore(&mut self, seq_id: SequenceId) -> Result<(), String> { 514 if !self.is_awaiting_restore(seq_id) { 515 return Err(format!( 516 "release_restore: sequence {seq_id} is stale or not awaiting a restore" 517 )); 518 } 519 if let Some(rec) = self.arena.get_mut(seq_id) { 520 rec.phase = SequencePhase::Waiting; 521 } 522 Ok(()) 523 } 524 525 /// Requests currently held by `hold_for_restore`. 526 pub fn awaiting_restore_count(&self) -> usize { 527 self.waiting_queue 528 .iter() 529 .filter(|&&id| self.is_awaiting_restore(id)) 530 .count() 531 } 532 533 /// Persistent KV (ADR 0003 section 6.3, review finding 4): admits a held 534 /// request whose first `restored` prompt tokens already have K/V in its 535 /// block table (assembled by the caller from restored chunks). It bypasses 536 /// the waiting-queue admission, which would take a ready table straight to 537 /// decode and so skip the unprocessed suffix. Instead the sequence enters 538 /// `running_sequences` in phase `Prefill` with `prompt_tokens_prefilled = 539 /// restored` and `is_prefilled = false`, so the ordinary "continuing 540 /// chunked prefill" branch schedules `prompt[restored..]` and the ordinary 541 /// completion fence marks the table ready after the last chunk. The table is 542 /// left `PrefillPending`, never completed here. 543 /// 544 /// Everything is checked first and any refusal changes nothing: the id must 545 /// be live and awaiting a restore, `0 < restored < prompt.len()` (at least 546 /// one token is always computed, so the fence always runs and the logits 547 /// come from this prompt), and the KV table must exist, be `PrefillPending` 548 /// and hold exactly `restored` tokens. No reference count is touched. 549 pub fn admit_restored_prefix( 550 &mut self, 551 seq_id: SequenceId, 552 restored: usize, 553 ) -> Result<(), String> { 554 let rec = self 555 .arena 556 .get(seq_id) 557 .filter(|rec| rec.phase == SequencePhase::AwaitingRestore) 558 .ok_or_else(|| { 559 format!( 560 "admit_restored_prefix: sequence {seq_id} is stale or not awaiting a restore" 561 ) 562 })?; 563 let prompt_len = rec.prompt.len(); 564 if restored == 0 || restored >= prompt_len { 565 return Err(format!( 566 "admit_restored_prefix: restored {restored} must be in 1..{prompt_len} \ 567 so at least one prompt token is computed" 568 )); 569 } 570 { 571 let kv = self.kv_manager.read(); 572 let table = kv.get_block_table(seq_id.to_u64()).ok_or_else(|| { 573 format!("admit_restored_prefix: sequence {seq_id} has no KV block table") 574 })?; 575 if table.prefill_state != PrefillState::PrefillPending { 576 return Err(format!( 577 "admit_restored_prefix: table is {:?}, expected PrefillPending", 578 table.prefill_state 579 )); 580 } 581 if table.total_tokens != restored { 582 return Err(format!( 583 "admit_restored_prefix: table holds {} tokens, restored is {restored}", 584 table.total_tokens 585 )); 586 } 587 } 588 let pos = self 589 .waiting_queue 590 .iter() 591 .position(|&id| id == seq_id) 592 .ok_or_else(|| { 593 format!("admit_restored_prefix: sequence {seq_id} is not in the waiting queue") 594 })?; 595 self.waiting_queue.remove(pos); 596 if let Some(rec) = self.arena.get_mut(seq_id) { 597 rec.phase = SequencePhase::Prefill; 598 rec.prompt_tokens_prefilled = restored; 599 rec.is_prefilled = false; 600 } 601 self.running_sequences.push(seq_id); 602 Ok(()) 603 } 604 605 /// Index in the waiting queue of the first request admission may consider: 606 /// requests held for a restore are skipped, not dropped, and do not block 607 /// the ones behind them. With nothing held this is always 0. 608 fn first_admittable_waiting(&self) -> Option { 609 self.waiting_queue 610 .iter() 611 .position(|&id| !self.is_awaiting_restore(id)) 612 } 613 614 /// Discards stale items from queue heads and internal lists without panics. 615 fn purge_stale_work(&mut self) { 616 while let Some(&id) = self.waiting_queue.front() { 617 if self.arena.is_stale(id) { 618 self.waiting_queue.pop_front(); 619 } else { 620 break; 621 } 622 } 623 624 while let Some(&id) = self.preempted_queue.front() { 625 if self.arena.is_stale(id) { 626 self.preempted_queue.pop_front(); 627 } else { 628 break; 629 } 630 } 631 632 let arena = &self.arena; 633 self.running_sequences.retain(|&id| !arena.is_stale(id)); 634 } 635 636 fn kv_reading(&self) -> KvReading { 637 let kv = self.kv_manager.read(); 638 let total_blocks = kv.total_block_count(); 639 let free_blocks = kv.available_blocks(); 640 KvReading { 641 total_blocks, 642 free_blocks, 643 allocated_blocks: total_blocks - free_blocks, 644 active_tables: kv.active_sequence_count(), 645 } 646 } 647 648 /// Builds the next scheduled batch enforcing chunked prefill budgets and watermark preemption. 649 /// 650 /// DUAL `serve.admit_preempt`: when an observer is installed, the decision 651 /// is traced while it is made and one `AdmitPreemptRecord` is handed to the 652 /// observer after it is final. Without an observer no trace exists and the 653 /// decision code path is the same as before the tap. 654 pub fn build_scheduled_batch(&mut self) -> Result, String> { 655 let mut trace = self.observer.is_some().then(AdmitPreemptTrace::default); 656 let result = self.build_scheduled_batch_traced(&mut trace); 657 if let (Some(observer), Some(trace)) = (self.observer.clone(), trace) { 658 let outcome = match &result { 659 Ok(Some(batch)) => BatchOutcome::Batch { 660 prefill_requests: batch.prefill_requests.len(), 661 decode_requests: batch.decode_requests.len(), 662 batch_tokens: batch 663 .prefill_requests 664 .iter() 665 .map(|r| r.prompt_tokens.len()) 666 .sum::() 667 + batch.decode_requests.len(), 668 }, 669 Ok(None) => BatchOutcome::Empty, 670 Err(e) => BatchOutcome::Error(e.clone()), 671 }; 672 let record = AdmitPreemptRecord { 673 site: SERVE_ADMIT_PREEMPT_SITE, 674 step_id: self.step_id, 675 limits: BatchLimits { 676 max_batch_size: self.config.max_batch_size, 677 max_batch_tokens: self.config.max_batch_tokens, 678 max_prefill_tokens: self.config.max_prefill_tokens, 679 prefill_chunk_size: self.config.prefill_chunk_size, 680 chunk_prefill: self.config.chunk_prefill, 681 watermark_blocks: self.config.watermark_blocks, 682 }, 683 arena_active_at_entry: trace.arena_active_at_entry, 684 kv_at_entry: trace.kv_at_entry, 685 below_watermark_at_entry: trace.below_watermark_at_entry, 686 kv_at_exit: self.kv_reading(), 687 running_count_at_exit: self.running_sequences.len(), 688 waiting_count_at_exit: self.waiting_queue.len(), 689 preempted_count_at_exit: self.preempted_queue.len(), 690 alternatives: trace.alternatives, 691 choice: AdmitPreemptChoice { 692 preempted: trace.preempted, 693 decode_scheduled: trace.decode_scheduled, 694 prefill_scheduled: trace.prefill_scheduled, 695 reprefill_requeued: trace.reprefill_requeued, 696 outcome, 697 }, 698 }; 699 observer.observe_admit_preempt(&record); 700 } 701 result 702 } 703 704 fn build_scheduled_batch_traced( 705 &mut self, 706 trace: &mut Option, 707 ) -> Result, String> { 708 self.step_id += 1; 709 self.purge_stale_work(); 710 711 if let Some(t) = trace.as_mut() { 712 t.arena_active_at_entry = self.arena.active_count(); 713 t.kv_at_entry = self.kv_reading(); 714 t.alternatives = AdmitPreemptAlternatives { 715 running_at_entry: self.running_sequences.clone(), 716 waiting_at_entry: self.waiting_queue.iter().copied().collect(), 717 preempted_at_entry: self.preempted_queue.iter().copied().collect(), 718 ..AdmitPreemptAlternatives::default() 719 }; 720 } 721 722 let mut prefill_requests = Vec::new(); 723 let mut decode_requests = Vec::new(); 724 let mut block_tables = HashMap::new(); 725 726 let mut current_tokens = 0; 727 let mut prefill_budget = self.config.max_prefill_tokens; 728 let mut preempted_this_step = false; 729 // New blocks promised to sequences admitted into decode this step 730 // (copy-on-write on their first token) but not allocated until the backend runs. 731 let mut reserved_blocks = 0usize; 732 733 // 1. Watermark Memory Pressure Check: Preempt lowest priority sequence if below watermark 734 { 735 let kv = self.kv_manager.read(); 736 let available = kv.available_blocks(); 737 if let Some(t) = trace.as_mut() { 738 t.below_watermark_at_entry = 739 available < self.config.watermark_blocks && !self.running_sequences.is_empty(); 740 } 741 if available < self.config.watermark_blocks && !self.running_sequences.is_empty() { 742 let mut candidates: Vec<(SequenceId, Priority)> = self 743 .running_sequences 744 .iter() 745 .filter_map(|&id| self.arena.get(id).map(|rec| (id, rec.priority))) 746 .collect(); 747 candidates.sort_by_key(|c| c.1 as u8); 748 if let Some(t) = trace.as_mut() { 749 t.alternatives.preemption_victims_considered = candidates 750 .iter() 751 .map(|&(seq, p)| PreemptionVictim { 752 seq, 753 priority: p as u8, 754 }) 755 .collect(); 756 } 757 758 if let Some((preempt_id, _)) = candidates.first() { 759 let preempt_id = *preempt_id; 760 drop(kv); 761 if let Some(pos) = self.running_sequences.iter().position(|&x| x == preempt_id) 762 { 763 if let Some(t) = trace.as_mut() { 764 t.preempted.push(preempt_id); 765 } 766 self.running_sequences.remove(pos); 767 let _ = self.kv_manager.write().free_sequence(preempt_id.to_u64()); 768 self.pending_backend_releases.push(preempt_id); 769 if let Some(rec) = self.arena.get_mut(preempt_id) { 770 rec.phase = SequencePhase::Preempted; 771 rec.prompt_tokens_prefilled = 0; 772 rec.is_prefilled = false; 773 } 774 self.preempted_queue.push_back(preempt_id); 775 self.metrics.preempted_requests += 1; 776 preempted_this_step = true; 777 } 778 } 779 } 780 } 781 782 // 2. Schedule active decode sequences and in-flight prefill chunks 783 let mut running_ids = self.running_sequences.clone(); 784 running_ids.sort(); 785 let mut needs_prefill: Vec = Vec::new(); 786 787 for seq_id in running_ids { 788 if decode_requests.len() + prefill_requests.len() >= self.config.max_batch_size { 789 if let Some(t) = trace.as_mut() { 790 t.alternatives.running_loop_stop = Some(LoopStop::BatchSizeReached); 791 } 792 break; 793 } 794 if current_tokens >= self.config.max_batch_tokens { 795 if let Some(t) = trace.as_mut() { 796 t.alternatives.running_loop_stop = Some(LoopStop::BatchTokensReached); 797 } 798 break; 799 } 800 801 let seq = match self.arena.get_mut(seq_id) { 802 Some(s) => s, 803 None => { 804 if let Some(t) = trace.as_mut() { 805 t.alternatives.running_examined.push(RunningItem { 806 seq: seq_id, 807 verdict: RunningVerdict::NoRecord, 808 }); 809 } 810 continue; 811 } 812 }; 813 814 if seq.is_prefilled { 815 // Active decode step, gated on computed K/V (PREFILL-GATE). 816 let table_state = self 817 .kv_manager 818 .read() 819 .get_block_table(seq_id.to_u64()) 820 .map(|t| (t.block_ids.clone(), t.is_prefill_ready())); 821 let mut verdict = RunningVerdict::DecodeNoTable; 822 if let Some((blocks, ready)) = table_state { 823 if prefill_gate_allows_decode(ready) { 824 block_tables.insert(seq_id.to_u64(), blocks); 825 decode_requests.push(seq_id.to_u64()); 826 current_tokens += 1; 827 verdict = RunningVerdict::Decode; 828 } else { 829 // The table exists but its K/V was never computed: 830 // send the sequence back for a real prefill, never decode. 831 seq.is_prefilled = false; 832 seq.prompt_tokens_prefilled = 0; 833 seq.phase = SequencePhase::Waiting; 834 needs_prefill.push(seq_id); 835 verdict = RunningVerdict::GateRefusedReprefill; 836 } 837 } 838 if let Some(t) = trace.as_mut() { 839 if verdict == RunningVerdict::Decode { 840 t.decode_scheduled.push(seq_id); 841 } 842 t.alternatives.running_examined.push(RunningItem { 843 seq: seq_id, 844 verdict, 845 }); 846 } 847 } else { 848 // Continuing chunked prefill 849 let total_prompt_len = seq.prefill_input_len(); 850 let remaining = total_prompt_len.saturating_sub(seq.prompt_tokens_prefilled); 851 let chunk_size = std::cmp::min(remaining, self.config.prefill_chunk_size); 852 let chunk_size = std::cmp::min(chunk_size, prefill_budget); 853 854 if chunk_size > 0 { 855 let start = seq.prompt_tokens_prefilled; 856 let end = start + chunk_size; 857 let chunk_tokens = seq.prefill_input()[start..end].to_vec(); 858 859 let chunk_req = SequenceRequest { 860 request_id: seq_id.to_u64(), 861 prompt_tokens: chunk_tokens, 862 sampling_params: seq.sampling_params.clone(), 863 arrival_time_ns: seq.arrival_time_ns, 864 priority: seq.priority as u8, 865 }; 866 867 if let Some(table) = self.kv_manager.read().get_block_table(seq_id.to_u64()) { 868 block_tables.insert(seq_id.to_u64(), table.block_ids.clone()); 869 } 870 871 prefill_requests.push(chunk_req); 872 current_tokens += chunk_size; 873 prefill_budget = prefill_budget.saturating_sub(chunk_size); 874 } 875 if let Some(t) = trace.as_mut() { 876 let verdict = if chunk_size > 0 { 877 t.prefill_scheduled.push((seq_id, chunk_size)); 878 RunningVerdict::ContinuePrefill { 879 chunk_len: chunk_size, 880 } 881 } else { 882 RunningVerdict::ContinuePrefillNoChunk 883 }; 884 t.alternatives.running_examined.push(RunningItem { 885 seq: seq_id, 886 verdict, 887 }); 888 } 889 } 890 } 891 892 // Sequences refused decode by the prefill gate: drop the uncomputed 893 // (possibly shared) table and requeue at the front for a fresh prefill. 894 for seq_id in needs_prefill { 895 if let Some(t) = trace.as_mut() { 896 t.reprefill_requeued.push(seq_id); 897 } 898 self.running_sequences.retain(|&x| x != seq_id); 899 let _ = self.kv_manager.write().free_sequence(seq_id.to_u64()); 900 self.pending_backend_releases.push(seq_id); 901 self.waiting_queue.push_front(seq_id); 902 } 903 904 // 3. Admit waiting or preempted requests if capacity permits and not under preemption pressure 905 if !preempted_this_step { 906 while decode_requests.len() + prefill_requests.len() < self.config.max_batch_size 907 && current_tokens < self.config.max_batch_tokens 908 && prefill_budget > 0 909 { 910 // Requests held for a restore are skipped, not dropped, and do not 911 // block the ones behind them. With nothing held the index is 0. 912 let waiting_idx = self.first_admittable_waiting(); 913 let (next_seq_id, is_preempted) = if let Some(&id) = self.preempted_queue.front() { 914 (id, true) 915 } else if let Some(idx) = waiting_idx { 916 (self.waiting_queue[idx], false) 917 } else { 918 break; 919 }; 920 let waiting_idx = waiting_idx.unwrap_or(0); 921 922 if self.arena.is_stale(next_seq_id) { 923 if let Some(t) = trace.as_mut() { 924 t.alternatives 925 .admission_examined 926 .push(AdmissionCandidate::before_kv( 927 next_seq_id, 928 is_preempted, 929 AdmissionVerdict::StaleDropped, 930 )); 931 } 932 if is_preempted { 933 self.preempted_queue.pop_front(); 934 } else { 935 self.waiting_queue.remove(waiting_idx); 936 } 937 continue; 938 } 939 940 let prompt_len = match self.arena.get(next_seq_id) { 941 Some(s) => s.prefill_input_len(), 942 None => { 943 if let Some(t) = trace.as_mut() { 944 t.alternatives 945 .admission_examined 946 .push(AdmissionCandidate::before_kv( 947 next_seq_id, 948 is_preempted, 949 AdmissionVerdict::MissingRecord, 950 )); 951 } 952 if is_preempted { 953 self.preempted_queue.pop_front(); 954 } else { 955 self.waiting_queue.remove(waiting_idx); 956 } 957 continue; 958 } 959 }; 960 961 // The KV manager is the only authority on how many NEW physical 962 // blocks this sequence needs (its own pool block size, blocks it 963 // already owns or shares, a pending copy-on-write). The need is 964 // read BEFORE the sequence leaves its queue. 965 let (needed_blocks, free_blocks, pool_blocks) = { 966 let kv = self.kv_manager.read(); 967 ( 968 kv.incremental_blocks_needed(next_seq_id.to_u64(), prompt_len), 969 kv.available_blocks(), 970 kv.total_block_count(), 971 ) 972 }; 973 // Blocks promised to sequences admitted earlier in this step 974 // that have not allocated them yet (forks entering decode). 975 let available = free_blocks.saturating_sub(reserved_blocks); 976 977 // Preempted sequences require headroom above watermark to prevent thrashing 978 let watermark_headroom = if is_preempted { 979 self.config.watermark_blocks 980 } else { 981 0 982 }; 983 let min_needed = needed_blocks + watermark_headroom; 984 985 // DUAL tap: one AdmissionCandidate per queue head examined, with 986 // the exact numbers compared above. Expands to nothing when no 987 // observer is installed (`trace` is None). 988 macro_rules! trace_admission { 989 ($verdict:expr) => { 990 if let Some(t) = trace.as_mut() { 991 t.alternatives.admission_examined.push(AdmissionCandidate { 992 seq: next_seq_id, 993 from_preempted_queue: is_preempted, 994 prompt_len, 995 needed_blocks, 996 free_blocks, 997 reserved_blocks, 998 watermark_headroom, 999 min_needed, 1000 pool_blocks, 1001 verdict: $verdict, 1002 }); 1003 } 1004 }; 1005 } 1006 1007 if available < min_needed { 1008 // Waiting is only honest while something can still free blocks. 1009 // A request larger than the whole pool, or one that waits with 1010 // nothing running and nothing scheduled, would wait forever. 1011 let nothing_can_free = self.running_sequences.is_empty() 1012 && decode_requests.is_empty() 1013 && prefill_requests.is_empty(); 1014 if min_needed > pool_blocks || nothing_can_free { 1015 trace_admission!(AdmissionVerdict::RefusedPoolExhausted); 1016 return Err(format!( 1017 "{KV_POOL_EXHAUSTED_PREFIX} admission of sequence {} needs {} new KV \ 1018 blocks (plus {} watermark) but only {} are free ({} in the pool) and \ 1019 nothing is running that could free more; the request stays queued", 1020 next_seq_id.to_u64(), 1021 needed_blocks, 1022 watermark_headroom, 1023 available, 1024 pool_blocks, 1025 )); 1026 } 1027 trace_admission!(AdmissionVerdict::WaitForBlocks); 1028 break; 1029 } 1030 1031 if is_preempted { 1032 self.preempted_queue.pop_front(); 1033 } else { 1034 self.waiting_queue.remove(waiting_idx); 1035 } 1036 1037 let seq = match self.arena.get_mut(next_seq_id) { 1038 Some(s) => s, 1039 None => continue, 1040 }; 1041 1042 let chunk_size = if self.config.chunk_prefill { 1043 std::cmp::min(prompt_len, self.config.prefill_chunk_size) 1044 } else { 1045 prompt_len 1046 }; 1047 let chunk_size = std::cmp::min(chunk_size, prefill_budget); 1048 1049 // Scheduler Zero-Copy Fork Invariant: Sequence admission must inspect existing block tables in KvCache. 1050 // Pre-forked branches skip redundant prefill and enter decode directly ONLY when the 1051 // shared prefix K/V was computed by a completed prefill (PREFILL-GATE). A block table 1052 // alone proves allocation, not computation: allocate_sequence only reserves and zeroes. 1053 let existing_table = self 1054 .kv_manager 1055 .read() 1056 .get_block_table(next_seq_id.to_u64()) 1057 .map(|t| (t.block_ids.clone(), t.is_prefill_ready())); 1058 1059 match existing_table { 1060 Some((blocks, ready)) if prefill_gate_allows_decode(ready) => { 1061 block_tables.insert(next_seq_id.to_u64(), blocks); 1062 seq.is_prefilled = true; 1063 seq.phase = SequencePhase::Decode; 1064 seq.prompt_tokens_prefilled = prompt_len; 1065 decode_requests.push(next_seq_id.to_u64()); 1066 current_tokens += 1; 1067 trace_admission!(AdmissionVerdict::AdmittedDecode); 1068 if let Some(t) = trace.as_mut() { 1069 t.decode_scheduled.push(next_seq_id); 1070 } 1071 reserved_blocks += needed_blocks; 1072 self.running_sequences.push(next_seq_id); 1073 // MUTANT ONLY (feature `dual_observer_mutant_changes_decision`): 1074 // an observer's presence stops admission after one grant. 1075 // The parity tests must FAIL with this feature on. 1076 if cfg!(feature = "dual_observer_mutant_changes_decision") 1077 && trace.is_some() 1078 { 1079 break; 1080 } 1081 continue; 1082 } 1083 Some(_) => { 1084 // Allocated but not computed: drop the table (and its share of 1085 // any parent blocks) and fall through to allocate + prefill. 1086 let _ = self.kv_manager.write().free_sequence(next_seq_id.to_u64()); 1087 } 1088 None => {} 1089 } 1090 1091 if chunk_size == 0 { 1092 trace_admission!(AdmissionVerdict::ChunkBudgetExhausted); 1093 if is_preempted { 1094 self.preempted_queue.push_front(next_seq_id); 1095 } else { 1096 self.waiting_queue.insert(waiting_idx, next_seq_id); 1097 } 1098 break; 1099 } 1100 1101 // Allocate blocks for admitted sequence 1102 let assigned_blocks = self 1103 .kv_manager 1104 .write() 1105 .allocate_sequence(next_seq_id.to_u64(), &seq.prefill_input())?; 1106 self.kv_manager 1107 .write() 1108 .mark_prefill_pending(next_seq_id.to_u64()) 1109 .map_err(|e| e.to_string())?; 1110 1111 let new_blocks = assigned_blocks.len(); 1112 block_tables.insert(next_seq_id.to_u64(), assigned_blocks); 1113 1114 let chunk_tokens = seq.prefill_input()[0..chunk_size].to_vec(); 1115 let chunk_req = SequenceRequest { 1116 request_id: next_seq_id.to_u64(), 1117 prompt_tokens: chunk_tokens, 1118 sampling_params: seq.sampling_params.clone(), 1119 arrival_time_ns: seq.arrival_time_ns, 1120 priority: seq.priority as u8, 1121 }; 1122 1123 prefill_requests.push(chunk_req); 1124 current_tokens += chunk_size; 1125 prefill_budget = prefill_budget.saturating_sub(chunk_size); 1126 1127 seq.phase = SequencePhase::Prefill; 1128 self.running_sequences.push(next_seq_id); 1129 trace_admission!(AdmissionVerdict::AdmittedPrefill { 1130 chunk_len: chunk_size, 1131 new_blocks, 1132 }); 1133 if let Some(t) = trace.as_mut() { 1134 t.prefill_scheduled.push((next_seq_id, chunk_size)); 1135 } 1136 // MUTANT ONLY (feature `dual_observer_mutant_changes_decision`), 1137 // see the decode admission above. 1138 if cfg!(feature = "dual_observer_mutant_changes_decision") && trace.is_some() { 1139 break; 1140 } 1141 } 1142 } 1143 1144 if prefill_requests.is_empty() && decode_requests.is_empty() { 1145 return Ok(None); 1146 } 1147 1148 Ok(Some(ScheduledBatch { 1149 prefill_requests, 1150 decode_requests, 1151 block_tables, 1152 step_id: self.step_id, 1153 })) 1154 } 1155 1156 /// Builds a structured zero-copy BatchPlan for native batch engines. 1157 pub fn build_batch_plan(&mut self) -> Result, String> { 1158 let batch = match self.build_scheduled_batch()? { 1159 Some(b) => b, 1160 None => return Ok(None), 1161 }; 1162 1163 let mut prefill_spans = Vec::new(); 1164 let mut decode_items = Vec::new(); 1165 let mut total_tokens = 0; 1166 1167 for req in &batch.prefill_requests { 1168 if let Ok(seq_id) = SequenceId::from_u64(req.request_id) { 1169 if let Some(record) = self.arena.get(seq_id) { 1170 let length = req.prompt_tokens.len(); 1171 prefill_spans.push(PrefillSpan { 1172 seq_id, 1173 start_pos: record.prompt_tokens_prefilled, 1174 length, 1175 }); 1176 total_tokens += length; 1177 } 1178 } 1179 } 1180 1181 for &req_id in &batch.decode_requests { 1182 if let Ok(seq_id) = SequenceId::from_u64(req_id) { 1183 if let Some(record) = self.arena.get(seq_id) { 1184 decode_items.push(DecodeItem { 1185 seq_id, 1186 token_pos: record.total_tokens(), 1187 }); 1188 total_tokens += 1; 1189 } 1190 } 1191 } 1192 1193 Ok(Some(BatchPlan { 1194 step_id: batch.step_id, 1195 prefill_spans, 1196 decode_items, 1197 total_tokens, 1198 })) 1199 } 1200 1201 /// Runs a model prefill over `prompt` for a KV sequence this scheduler does 1202 /// not own (a swarm root, which is never decoded), then fires the 1203 /// completion fence. The prompt is sent in chunks of `prefill_chunk_size` 1204 /// (capped by `max_prefill_tokens`). PrefillReady is set only after every 1205 /// chunk's `execute_step` returned Ok and the backend reported processing 1206 /// the whole chunk; any error leaves the table not ready. 1207 /// 1208 /// Returns Ok(None) when the table is already ready (nothing to compute), 1209 /// Ok(Some(metrics)) after a completed prefill. 1210 pub async fn prefill_detached( 1211 &mut self, 1212 backend: &mut (dyn AienInferenceBackend + '_), 1213 kv_seq_id: u64, 1214 prompt: &[u32], 1215 ) -> Result, String> { 1216 let blocks = { 1217 let mut kv = self.kv_manager.write(); 1218 if kv.get_block_table(kv_seq_id).is_none() { 1219 kv.allocate_sequence(kv_seq_id, prompt)?; 1220 } 1221 let table = kv.get_block_table(kv_seq_id).ok_or_else(|| { 1222 PrefillGateError::UnknownSequence { seq_id: kv_seq_id }.to_string() 1223 })?; 1224 if table.is_prefill_ready() { 1225 return Ok(None); 1226 } 1227 let blocks = table.block_ids.clone(); 1228 kv.mark_prefill_pending(kv_seq_id) 1229 .map_err(|e| e.to_string())?; 1230 blocks 1231 }; 1232 1233 let chunk_len = self 1234 .config 1235 .prefill_chunk_size 1236 .min(self.config.max_prefill_tokens) 1237 .max(1); 1238 let t0 = Instant::now(); 1239 let mut prefill_tokens = 0usize; 1240 1241 for span in prompt.chunks(chunk_len) { 1242 self.step_id += 1; 1243 let mut block_tables = HashMap::new(); 1244 block_tables.insert(kv_seq_id, blocks.clone()); 1245 let batch = ScheduledBatch { 1246 prefill_requests: vec![SequenceRequest { 1247 request_id: kv_seq_id, 1248 prompt_tokens: span.to_vec(), 1249 sampling_params: aien_abi_core::SamplingParams::default(), 1250 arrival_time_ns: 0, 1251 priority: Priority::Normal as u8, 1252 }], 1253 decode_requests: Vec::new(), 1254 block_tables, 1255 step_id: self.step_id, 1256 }; 1257 let (_outputs, metrics) = backend.execute_step(&batch).await?; 1258 if metrics.prefill_tokens_processed < span.len() { 1259 return Err(format!( 1260 "prefill gate: backend processed {} of {} prompt tokens for sequence {}; not marking ready", 1261 metrics.prefill_tokens_processed, 1262 span.len(), 1263 kv_seq_id 1264 )); 1265 } 1266 prefill_tokens += span.len(); 1267 } 1268 1269 // PREFILL-GATE completion fence: the forward over the whole prompt span completed. 1270 self.kv_manager 1271 .write() 1272 .complete_prefill(kv_seq_id) 1273 .map_err(|e| e.to_string())?; 1274 1275 self.metrics.total_prefill_tokens += prefill_tokens as u64; 1276 let active_kv_blocks = self.kv_manager.read().allocated_block_count(); 1277 Ok(Some(StepMetrics { 1278 prefill_tokens_processed: prefill_tokens, 1279 decode_tokens_emitted: 0, 1280 step_latency_us: t0.elapsed().as_micros() as u64, 1281 active_kv_blocks, 1282 })) 1283 } 1284 1285 /// Advances the engine by one step using the configured backend. 1286 pub async fn step( 1287 &mut self, 1288 backend: &mut (dyn AienInferenceBackend + '_), 1289 ) -> Result, StepMetrics)>, String> { 1290 let batch = self.build_scheduled_batch()?; 1291 // Sequences preempted (or sent back for a fresh prefill) since the last 1292 // step: their KV is freed and no step is executing, so the backend may 1293 // drop its per-sequence state now. Done before `execute_step`, so a 1294 // resumed sequence is prefilled from position 0, not a stale one. 1295 for seq_id in self.take_pending_backend_releases() { 1296 backend.release_sequence(seq_id.to_u64())?; 1297 } 1298 let Some(batch) = batch else { 1299 return Ok(None); 1300 }; 1301 1302 let t0 = Instant::now(); 1303 let (outputs, metrics) = backend.execute_step(&batch).await?; 1304 let step_latency = t0.elapsed().as_micros() as u64; 1305 1306 // Update prefill progress for chunked sequences 1307 for prefill_req in &batch.prefill_requests { 1308 if let Ok(seq_id) = SequenceId::from_u64(prefill_req.request_id) { 1309 if let Some(seq) = self.arena.get_mut(seq_id) { 1310 if !seq.is_prefilled { 1311 seq.prompt_tokens_prefilled += prefill_req.prompt_tokens.len(); 1312 if seq.prompt_tokens_prefilled >= seq.prefill_input_len() { 1313 seq.is_prefilled = true; 1314 seq.phase = SequencePhase::Decode; 1315 // PREFILL-GATE completion fence: execute_step returned Ok 1316 // for the final prompt chunk, so the K/V is computed. 1317 let _ = self 1318 .kv_manager 1319 .write() 1320 .complete_prefill(prefill_req.request_id); 1321 } 1322 } 1323 } 1324 } 1325 } 1326 1327 let mut final_outputs = Vec::new(); 1328 1329 for output in outputs { 1330 match output { 1331 DecodeOutput::Token { 1332 request_id, 1333 token_id, 1334 logprob, 1335 } => { 1336 let mut is_finished = false; 1337 let mut finish_reason = FinishReason::StopToken; 1338 let mut total_tokens = 0; 1339 let mut should_emit_token = false; 1340 1341 if let Ok(seq_id) = SequenceId::from_u64(request_id) { 1342 if let Some(seq) = self.arena.get_mut(seq_id) { 1343 if seq.is_prefilled { 1344 should_emit_token = true; 1345 seq.tokens_generated += 1; 1346 seq.generated_tokens.push(token_id); 1347 total_tokens = seq.tokens_generated; 1348 1349 if seq.sampling_params.stop_token_ids.contains(&token_id) { 1350 is_finished = true; 1351 finish_reason = FinishReason::StopToken; 1352 } else if seq.tokens_generated >= seq.sampling_params.max_tokens { 1353 is_finished = true; 1354 finish_reason = FinishReason::LengthLimit; 1355 } else if !backend.manages_kv_cache() { 1356 // Append token in KV manager if backend does not manage it directly 1357 let append_result = 1358 self.kv_manager.write().append_token(request_id); 1359 if append_result.is_err() { 1360 is_finished = true; 1361 finish_reason = FinishReason::Preempted; 1362 } 1363 } 1364 1365 if let Some(sink_id) = seq.sink_id { 1366 self.completion_router.emit( 1367 sink_id, 1368 CompletionEvent::Token { 1369 seq_id, 1370 token: token_id, 1371 }, 1372 ); 1373 } 1374 } 1375 } 1376 1377 if is_finished { 1378 if let Some(pos) = 1379 self.running_sequences.iter().position(|&x| x == seq_id) 1380 { 1381 self.running_sequences.remove(pos); 1382 } 1383 let finished_sink = self.arena.get(seq_id).and_then(|seq| seq.sink_id); 1384 if finish_reason == FinishReason::Preempted { 1385 let _ = self.kv_manager.write().free_sequence(request_id); 1386 self.pending_backend_releases.push(seq_id); 1387 if let Some(seq) = self.arena.get_mut(seq_id) { 1388 seq.phase = SequencePhase::Preempted; 1389 seq.prompt_tokens_prefilled = 0; 1390 seq.is_prefilled = false; 1391 } 1392 self.preempted_queue.push_back(seq_id); 1393 self.metrics.preempted_requests += 1; 1394 } else { 1395 // Finish transaction: hook, then free, one KV guard (ADR 0003 6.1). 1396 self.finish_kv_transaction(&*backend, seq_id, finish_reason); 1397 self.arena.free_sequence(seq_id); 1398 self.metrics.finished_requests += 1; 1399 } 1400 1401 final_outputs.push(DecodeOutput::Finished { 1402 request_id, 1403 reason: finish_reason, 1404 total_tokens, 1405 }); 1406 // sc#294: taken on every finish, listened to or not. 1407 let decoding = backend.take_decode_observation(request_id); 1408 // sc#337: the op counters at this finish, listened to or not. 1409 let ops = backend.op_evidence(); 1410 if let Some(sink_id) = finished_sink { 1411 self.completion_router.emit( 1412 sink_id, 1413 CompletionEvent::Finished { 1414 seq_id, 1415 finish_reason, 1416 total_tokens, 1417 decoding, 1418 ops, 1419 }, 1420 ); 1421 } 1422 } else if should_emit_token { 1423 final_outputs.push(DecodeOutput::Token { 1424 request_id, 1425 token_id, 1426 logprob, 1427 }); 1428 } 1429 } 1430 } 1431 DecodeOutput::Finished { 1432 request_id, 1433 reason, 1434 total_tokens, 1435 } => { 1436 if let Ok(seq_id) = SequenceId::from_u64(request_id) { 1437 if let Some(pos) = self.running_sequences.iter().position(|&x| x == seq_id) 1438 { 1439 self.running_sequences.remove(pos); 1440 } 1441 let finished_sink = self.arena.get(seq_id).and_then(|seq| seq.sink_id); 1442 // Backend-originated finish: same transaction (ADR 0003 6.1). 1443 self.finish_kv_transaction(&*backend, seq_id, reason); 1444 self.arena.free_sequence(seq_id); 1445 self.metrics.finished_requests += 1; 1446 // sc#294: taken on every finish, listened to or not. 1447 let decoding = backend.take_decode_observation(request_id); 1448 // sc#337: the op counters at this finish, listened to or not. 1449 let ops = backend.op_evidence(); 1450 if let Some(sink_id) = finished_sink { 1451 self.completion_router.emit( 1452 sink_id, 1453 CompletionEvent::Finished { 1454 seq_id, 1455 finish_reason: reason, 1456 total_tokens, 1457 decoding, 1458 ops, 1459 }, 1460 ); 1461 } 1462 } 1463 final_outputs.push(DecodeOutput::Finished { 1464 request_id, 1465 reason, 1466 total_tokens, 1467 }); 1468 } 1469 } 1470 } 1471 1472 self.metrics.total_steps += 1; 1473 self.metrics.total_prefill_tokens += metrics.prefill_tokens_processed as u64; 1474 self.metrics.total_decode_tokens += metrics.decode_tokens_emitted as u64; 1475 1476 if metrics.prefill_tokens_processed > 0 && self.config.chunk_prefill { 1477 self.metrics.chunked_prefill_steps += 1; 1478 } 1479 1480 let total_steps = self.metrics.total_steps as f64; 1481 self.metrics.avg_step_latency_us = (self.metrics.avg_step_latency_us * (total_steps - 1.0) 1482 + step_latency as f64) 1483 / total_steps; 1484 1485 let active_kv_blocks = self.kv_manager.read().allocated_block_count(); 1486 1487 Ok(Some(( 1488 final_outputs, 1489 StepMetrics { 1490 prefill_tokens_processed: metrics.prefill_tokens_processed, 1491 decode_tokens_emitted: metrics.decode_tokens_emitted, 1492 step_latency_us: step_latency, 1493 active_kv_blocks, 1494 }, 1495 ))) 1496 } 1497 } 1498 1499 #[cfg(test)] 1500 mod tests { 1501 use super::*; 1502 use aien_abi_core::SamplingParams; 1503 use aien_inference_abi::MockInferenceBackend; 1504 use aien_kv_cache::create_shared_kv_manager; 1505 1506 #[tokio::test] 1507 async fn test_scheduler_lifecycle_and_stale_work_rejection() { 1508 let kv_manager = create_shared_kv_manager(64, 16); 1509 let config = SchedulerConfig::default(); 1510 let mut scheduler = AienScheduler::new(config, kv_manager); 1511 let mut backend = MockInferenceBackend::new(10); 1512 1513 let req = SequenceRequest { 1514 request_id: 1, 1515 prompt_tokens: vec![1, 2, 3, 4], 1516 sampling_params: SamplingParams { 1517 temperature: 0.0, 1518 top_p: 1.0, 1519 max_tokens: 3, 1520 stop_token_ids: vec![], 1521 }, 1522 arrival_time_ns: 0, 1523 priority: 1, 1524 }; 1525 1526 let seq_id = scheduler.submit_request(req); 1527 assert_eq!(scheduler.waiting_count(), 1); 1528 1529 // Step 1: Admits and prefills (emits token 1) 1530 let res1 = scheduler.step(&mut backend).await.unwrap().unwrap(); 1531 assert_eq!(res1.0.len(), 1); 1532 assert_eq!(scheduler.running_count(), 1); 1533 assert_eq!(res1.1.prefill_tokens_processed, 4); 1534 1535 // Manually simulate a stale work ticket in waiting queue: 1536 let fake_stale_id = SequenceId::new(seq_id.slot, seq_id.generation + 10).unwrap(); 1537 scheduler.waiting_queue.push_back(fake_stale_id); 1538 1539 // Step 2: Executes decode token 2 and silently discards fake_stale_id without error or panic 1540 let res2 = scheduler.step(&mut backend).await.unwrap().unwrap(); 1541 assert_eq!(res2.0.len(), 1); 1542 assert_eq!(scheduler.waiting_count(), 0); // Stale work was discarded 1543 1544 // Step 3: Hits max_tokens (3) and finishes 1545 let res3 = scheduler.step(&mut backend).await.unwrap().unwrap(); 1546 assert_eq!(res3.0.len(), 1); 1547 match &res3.0[0] { 1548 DecodeOutput::Finished { 1549 request_id, 1550 reason, 1551 total_tokens, 1552 } => { 1553 assert_eq!(*request_id, seq_id.to_u64()); 1554 assert_eq!(*reason, FinishReason::LengthLimit); 1555 assert_eq!(*total_tokens, 3); 1556 } 1557 _ => panic!("Expected Finished output"), 1558 } 1559 assert_eq!(scheduler.running_count(), 0); 1560 assert_eq!(scheduler.metrics().finished_requests, 1); 1561 } 1562 1563 #[tokio::test] 1564 async fn test_chunked_prefill_segmentation() { 1565 let kv_manager = create_shared_kv_manager(100, 16); 1566 let config = SchedulerConfig { 1567 max_batch_size: 16, 1568 max_batch_tokens: 1024, 1569 max_prefill_tokens: 512, 1570 prefill_chunk_size: 64, 1571 chunk_prefill: true, 1572 watermark_blocks: 2, 1573 }; 1574 let mut scheduler = AienScheduler::new(config, kv_manager); 1575 let mut backend = MockInferenceBackend::new(10); 1576 1577 let req = SequenceRequest { 1578 request_id: 100, 1579 prompt_tokens: (0..128).collect(), 1580 sampling_params: SamplingParams { 1581 temperature: 0.0, 1582 top_p: 1.0, 1583 max_tokens: 2, 1584 stop_token_ids: vec![], 1585 }, 1586 arrival_time_ns: 0, 1587 priority: 1, 1588 }; 1589 1590 scheduler.submit_request(req); 1591 1592 // Step 1: Processes chunk 1 (64 tokens) 1593 let res1 = scheduler.step(&mut backend).await.unwrap().unwrap(); 1594 assert_eq!(res1.1.prefill_tokens_processed, 64); 1595 assert_eq!(scheduler.running_count(), 1); 1596 1597 // Step 2: Processes chunk 2 (64 tokens, completes prompt) 1598 let res2 = scheduler.step(&mut backend).await.unwrap().unwrap(); 1599 assert_eq!(res2.1.prefill_tokens_processed, 64); 1600 1601 // Step 3: Decode begins 1602 let res3 = scheduler.step(&mut backend).await.unwrap().unwrap(); 1603 assert_eq!(res3.1.decode_tokens_emitted, 1); 1604 } 1605 1606 #[tokio::test] 1607 async fn test_watermark_pressure_preemption() { 1608 let kv_manager = create_shared_kv_manager(6, 16); 1609 let config = SchedulerConfig { 1610 max_batch_size: 4, 1611 max_batch_tokens: 1024, 1612 max_prefill_tokens: 512, 1613 prefill_chunk_size: 128, 1614 chunk_prefill: false, 1615 watermark_blocks: 3, 1616 }; 1617 let mut scheduler = AienScheduler::new(config, kv_manager.clone()); 1618 let mut backend = MockInferenceBackend::new(10); 1619 1620 scheduler.submit_request(SequenceRequest { 1621 request_id: 1, 1622 prompt_tokens: (0..32).collect(), 1623 sampling_params: SamplingParams { 1624 temperature: 0.0, 1625 top_p: 1.0, 1626 max_tokens: 10, 1627 stop_token_ids: vec![], 1628 }, 1629 arrival_time_ns: 0, 1630 priority: 5, 1631 }); 1632 1633 scheduler.submit_request(SequenceRequest { 1634 request_id: 2, 1635 prompt_tokens: (0..32).collect(), 1636 sampling_params: SamplingParams { 1637 temperature: 0.0, 1638 top_p: 1.0, 1639 max_tokens: 10, 1640 stop_token_ids: vec![], 1641 }, 1642 arrival_time_ns: 0, 1643 priority: 1, 1644 }); 1645 1646 // Step 1: Admits both 1647 scheduler.step(&mut backend).await.unwrap(); 1648 1649 // Step 2: Memory pressure triggers preemption of lower priority 1650 scheduler.step(&mut backend).await.unwrap(); 1651 assert_eq!(scheduler.metrics().preempted_requests, 1); 1652 assert_eq!(scheduler.preempted_count(), 1); 1653 assert_eq!(scheduler.running_count(), 1); 1654 } 1655 1656 // PREFILL-GATE unit tests (new readiness API). 1657 1658 fn gate_request(request_id: u64, prompt: Vec, max_tokens: usize) -> SequenceRequest { 1659 SequenceRequest { 1660 request_id, 1661 prompt_tokens: prompt, 1662 sampling_params: SamplingParams { 1663 temperature: 0.0, 1664 top_p: 1.0, 1665 max_tokens, 1666 stop_token_ids: vec![], 1667 }, 1668 arrival_time_ns: 0, 1669 priority: 1, 1670 } 1671 } 1672 1673 #[tokio::test] 1674 async fn test_prefill_gate_scheduler_fence_marks_ready_only_after_last_chunk() { 1675 let kv_manager = create_shared_kv_manager(100, 16); 1676 let config = SchedulerConfig { 1677 max_batch_size: 16, 1678 max_batch_tokens: 1024, 1679 max_prefill_tokens: 512, 1680 prefill_chunk_size: 64, 1681 chunk_prefill: true, 1682 watermark_blocks: 2, 1683 }; 1684 let mut scheduler = AienScheduler::new(config, kv_manager.clone()); 1685 let mut backend = MockInferenceBackend::new(0); 1686 1687 let seq = scheduler.submit_request(gate_request(0, (0..128).collect(), 2)); 1688 let id = seq.to_u64(); 1689 1690 // Chunk 1 of 2: prefill issued, not complete. 1691 scheduler.step(&mut backend).await.unwrap().unwrap(); 1692 assert_eq!( 1693 kv_manager.read().prefill_state(id), 1694 Some(aien_kv_cache::PrefillState::PrefillPending), 1695 "a half-prefilled table must not be ready" 1696 ); 1697 1698 // Chunk 2 of 2: completion fence fires. 1699 scheduler.step(&mut backend).await.unwrap().unwrap(); 1700 assert_eq!( 1701 kv_manager.read().prefill_state(id), 1702 Some(aien_kv_cache::PrefillState::PrefillReady) 1703 ); 1704 1705 let res3 = scheduler.step(&mut backend).await.unwrap().unwrap(); 1706 assert_eq!(res3.1.decode_tokens_emitted, 1); 1707 } 1708 1709 #[test] 1710 fn test_prefill_gate_ready_fork_enters_decode_directly() { 1711 // Positive control: a branch forked from a computed root decodes 1712 // without redundant prefill. The gate is not "never decode". 1713 let kv_manager = create_shared_kv_manager(64, 16); 1714 let mut scheduler = AienScheduler::new(SchedulerConfig::default(), kv_manager.clone()); 1715 1716 let root = SequenceId::new(1, 1).unwrap().to_u64(); 1717 let child = SequenceId::new(2, 1).unwrap().to_u64(); 1718 let prompt: Vec = (0..20).collect(); 1719 { 1720 let mut kv = kv_manager.write(); 1721 kv.allocate_sequence(root, &prompt).unwrap(); 1722 kv.mark_prefill_pending(root).unwrap(); 1723 kv.complete_prefill(root).unwrap(); 1724 kv.fork_prefilled(root, child).unwrap(); 1725 } 1726 1727 scheduler.submit_request(gate_request(child, prompt, 4)); 1728 let batch = scheduler.build_scheduled_batch().unwrap().unwrap(); 1729 assert!(batch.decode_requests.contains(&child)); 1730 assert!(batch.prefill_requests.is_empty()); 1731 } 1732 1733 #[tokio::test] 1734 async fn test_prefill_gate_running_sequence_with_unready_table_is_reprefilled() { 1735 let kv_manager = create_shared_kv_manager(64, 16); 1736 let mut scheduler = AienScheduler::new(SchedulerConfig::default(), kv_manager.clone()); 1737 let mut backend = MockInferenceBackend::new(0); 1738 1739 let prompt: Vec = vec![1, 2, 3, 4]; 1740 let seq = scheduler.submit_request(gate_request(0, prompt.clone(), 8)); 1741 let id = seq.to_u64(); 1742 scheduler.step(&mut backend).await.unwrap().unwrap(); 1743 assert!(kv_manager 1744 .read() 1745 .get_block_table(id) 1746 .unwrap() 1747 .is_prefill_ready()); 1748 // The step that completed the prefill also sampled (and emitted) the 1749 // first token, so the sequence now carries one generated token. 1750 let generated = scheduler.arena.get(seq).unwrap().generated_tokens.clone(); 1751 assert_eq!(generated.len(), 1, "prefill completion samples one token"); 1752 1753 // Counterexample: the running sequence's table is replaced by an 1754 // allocated-but-uncomputed one. It must be prefilled again, not decoded. 1755 { 1756 let mut kv = kv_manager.write(); 1757 kv.free_sequence(id).unwrap(); 1758 kv.allocate_sequence(id, &prompt).unwrap(); 1759 } 1760 let batch = scheduler.build_scheduled_batch().unwrap().unwrap(); 1761 assert!( 1762 !batch.decode_requests.contains(&id), 1763 "PREFILL_GATE_VIOLATION: running sequence decoded over an uncomputed table" 1764 ); 1765 // The re-prefill covers the prompt and the already-emitted token, so the 1766 // next sample is a new token. Prompt-only would re-sample and re-emit it. 1767 let expected: Vec = prompt.iter().copied().chain(generated).collect(); 1768 assert!(batch 1769 .prefill_requests 1770 .iter() 1771 .any(|r| r.request_id == id && r.prompt_tokens == expected)); 1772 } 1773 1774 #[test] 1775 fn test_prefill_gate_reprefill_without_generated_tokens_is_exactly_the_prompt() { 1776 // A sequence refused by the gate before it generated anything must be 1777 // re-prefilled with exactly its prompt, nothing more. 1778 let kv_manager = create_shared_kv_manager(64, 16); 1779 let mut scheduler = AienScheduler::new(SchedulerConfig::default(), kv_manager.clone()); 1780 1781 let root = SequenceId::new(1, 1).unwrap().to_u64(); 1782 let child = SequenceId::new(2, 1).unwrap().to_u64(); 1783 let prompt: Vec = (0..20).collect(); 1784 { 1785 let mut kv = kv_manager.write(); 1786 kv.allocate_sequence(root, &prompt).unwrap(); 1787 kv.mark_prefill_pending(root).unwrap(); 1788 kv.complete_prefill(root).unwrap(); 1789 kv.fork_prefilled(root, child).unwrap(); 1790 } 1791 let seq = scheduler.submit_request(gate_request(child, prompt.clone(), 4)); 1792 let batch = scheduler.build_scheduled_batch().unwrap().unwrap(); 1793 assert!(batch.decode_requests.contains(&child)); 1794 assert!(scheduler 1795 .arena 1796 .get(seq) 1797 .unwrap() 1798 .generated_tokens 1799 .is_empty()); 1800 1801 { 1802 let mut kv = kv_manager.write(); 1803 kv.free_sequence(child).unwrap(); 1804 kv.allocate_sequence(child, &prompt).unwrap(); 1805 } 1806 let batch = scheduler.build_scheduled_batch().unwrap().unwrap(); 1807 assert!(!batch.decode_requests.contains(&child)); 1808 assert!(batch 1809 .prefill_requests 1810 .iter() 1811 .any(|r| r.request_id == child && r.prompt_tokens == prompt)); 1812 } 1813 }