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 / dual_observer.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 | //! DUAL decision-site observer for `serve.admit_preempt` (ARCH-0031 §7.3, |
| 17 | //! DUAL-3 instrumentation). READ-ONLY by construction. |
| 18 | //! |
| 19 | //! `AienScheduler::build_scheduled_batch` is the one place in this crate that |
| 20 | //! decides admission, the preemption victim and the prefill chunk allocation. |
| 21 | //! This module lets a caller install a [`DecisionObserver`] that receives, |
| 22 | //! after each decision, one immutable [`AdmitPreemptRecord`] describing the |
| 23 | //! alternatives the scheduler actually looked at, the choice it made, and the |
| 24 | //! resource readings it made the choice with. |
| 25 | //! |
| 26 | //! What the tap cannot do: |
| 27 | //! |
| 28 | //! - It holds no reference to the scheduler, the KV manager or the arena. The |
| 29 | //! hook receives `&AdmitPreemptRecord` (a copy of already-made decisions) and |
| 30 | //! returns `()`. There is no return value the scheduler reads. |
| 31 | //! - With no observer installed (`None`, the default) every tracing branch is |
| 32 | //! skipped and the decision code runs exactly as before. The parity tests in |
| 33 | //! `tests/dual_decision_parity.rs` and `tests/dual_observer_parity.rs` hold |
| 34 | //! the serialized decisions byte-for-byte equal in both configurations. |
| 35 | //! - No field of a record is an authority input anywhere. A consumer that |
| 36 | //! reads one as a gate input fails its gate (ADR 0031 §6). |
| 37 | //! |
| 38 | //! The record names the production state machine's own identities |
| 39 | //! (`SequenceId`, step counter, KV block counts). It introduces no second |
| 40 | //! ledger: every number is copied from a local the scheduler computed for |
| 41 | //! its own decision, at the instant it computed it. |
| 42 | //! |
| 43 | //! ```compile_fail |
| 44 | //! // Negative control, held by the type system: an observer cannot change |
| 45 | //! // the record it is shown. `observe_admit_preempt` takes `&AdmitPreemptRecord`. |
| 46 | //! use aien_scheduler::dual_observer::{AdmitPreemptRecord, DecisionObserver}; |
| 47 | //! struct Tamper; |
| 48 | //! impl DecisionObserver for Tamper { |
| 49 | //! fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { |
| 50 | //! record.choice.preempted.clear(); |
| 51 | //! } |
| 52 | //! } |
| 53 | //! ``` |
| 54 | //! |
| 55 | //! ```compile_fail |
| 56 | //! // Negative control, held by the type system: the hook returns `()`, so an |
| 57 | //! // observer cannot hand a different choice back to the scheduler. |
| 58 | //! use aien_scheduler::dual_observer::{AdmitPreemptChoice, AdmitPreemptRecord, DecisionObserver}; |
| 59 | //! struct Override; |
| 60 | //! impl DecisionObserver for Override { |
| 61 | //! fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) -> AdmitPreemptChoice { |
| 62 | //! record.choice.clone() |
| 63 | //! } |
| 64 | //! } |
| 65 | //! ``` |
| 66 | |
| 67 | use crate::SequenceId; |
| 68 | use serde::Serialize; |
| 69 | use std::sync::Mutex; |
| 70 | |
| 71 | /// Registered decision-site id (DUAL_CURRENT_STATE §4). |
| 72 | pub const SERVE_ADMIT_PREEMPT_SITE: &str = "serve.admit_preempt"; |
| 73 | |
| 74 | /// Scheduler limits in force for the decision, copied from `SchedulerConfig`. |
| 75 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 76 | pub struct BatchLimits { |
| 77 | pub max_batch_size: usize, |
| 78 | pub max_batch_tokens: usize, |
| 79 | pub max_prefill_tokens: usize, |
| 80 | pub prefill_chunk_size: usize, |
| 81 | pub chunk_prefill: bool, |
| 82 | pub watermark_blocks: usize, |
| 83 | } |
| 84 | |
| 85 | /// KV pool reading. `free_blocks` is `AienKvManager::available_blocks`, |
| 86 | /// `total_blocks` is `total_block_count`, `active_tables` is |
| 87 | /// `active_sequence_count`. `allocated_blocks` is `total - free`, the same |
| 88 | /// arithmetic as `allocated_block_count`. |
| 89 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] |
| 90 | pub struct KvReading { |
| 91 | pub total_blocks: usize, |
| 92 | pub free_blocks: usize, |
| 93 | pub allocated_blocks: usize, |
| 94 | pub active_tables: usize, |
| 95 | } |
| 96 | |
| 97 | /// One running sequence the watermark check ranked as a preemption victim, |
| 98 | /// in the order the scheduler sorted them (lowest priority first; equal |
| 99 | /// priorities keep their `running_sequences` order, `sort_by_key` is stable). |
| 100 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 101 | pub struct PreemptionVictim { |
| 102 | pub seq: SequenceId, |
| 103 | pub priority: u8, |
| 104 | } |
| 105 | |
| 106 | /// What step 2 of `build_scheduled_batch` did with one running sequence. |
| 107 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 108 | pub enum RunningVerdict { |
| 109 | /// Arena has no record for the id (skipped). |
| 110 | NoRecord, |
| 111 | /// Prefilled, table ready: scheduled for one decode token. |
| 112 | Decode, |
| 113 | /// Prefilled flag set but the table was never computed: sent back to the |
| 114 | /// waiting queue head for a fresh prefill (PREFILL-GATE). |
| 115 | GateRefusedReprefill, |
| 116 | /// In-flight chunked prefill: this many prompt tokens scheduled now. |
| 117 | ContinuePrefill { chunk_len: usize }, |
| 118 | /// In-flight chunked prefill but no chunk fit (remaining or budget was 0). |
| 119 | ContinuePrefillNoChunk, |
| 120 | /// Prefilled sequence whose table is missing from the KV manager (skipped). |
| 121 | DecodeNoTable, |
| 122 | } |
| 123 | |
| 124 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 125 | pub struct RunningItem { |
| 126 | pub seq: SequenceId, |
| 127 | pub verdict: RunningVerdict, |
| 128 | } |
| 129 | |
| 130 | /// Why the running-sequence loop stopped before examining every running id. |
| 131 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 132 | pub enum LoopStop { |
| 133 | BatchSizeReached, |
| 134 | BatchTokensReached, |
| 135 | } |
| 136 | |
| 137 | /// What step 3 of `build_scheduled_batch` did with one queue head. |
| 138 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 139 | pub enum AdmissionVerdict { |
| 140 | /// Stale id at the queue head: dropped, loop continues. |
| 141 | StaleDropped, |
| 142 | /// Arena record missing: dropped, loop continues. |
| 143 | MissingRecord, |
| 144 | /// `available < min_needed` while something running could free blocks: |
| 145 | /// the sequence stays queued, loop stops. |
| 146 | WaitForBlocks, |
| 147 | /// `available < min_needed` and nothing can free blocks (or the need |
| 148 | /// exceeds the whole pool): `build_scheduled_batch` returned `Err`. |
| 149 | RefusedPoolExhausted, |
| 150 | /// Existing block table with computed K/V (a fork): entered decode |
| 151 | /// directly, reserving `needed_blocks` for its first copy-on-write. |
| 152 | AdmittedDecode, |
| 153 | /// Allocated `new_blocks` physical blocks and scheduled the first |
| 154 | /// `chunk_len` prompt tokens for prefill. |
| 155 | AdmittedPrefill { chunk_len: usize, new_blocks: usize }, |
| 156 | /// Prefill budget left no room for a first chunk: pushed back to its |
| 157 | /// queue head, loop stops. |
| 158 | ChunkBudgetExhausted, |
| 159 | } |
| 160 | |
| 161 | /// One queue head examined by the admission loop, with the exact numbers the |
| 162 | /// scheduler compared. Resource fields are zero for verdicts reached before |
| 163 | /// the KV manager was consulted (`StaleDropped`, `MissingRecord`). |
| 164 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 165 | pub struct AdmissionCandidate { |
| 166 | pub seq: SequenceId, |
| 167 | pub from_preempted_queue: bool, |
| 168 | pub prompt_len: usize, |
| 169 | /// `AienKvManager::incremental_blocks_needed(seq, prompt_len)`. |
| 170 | pub needed_blocks: usize, |
| 171 | /// `AienKvManager::available_blocks()` at that instant. |
| 172 | pub free_blocks: usize, |
| 173 | /// Blocks promised to sequences admitted earlier in this same step. |
| 174 | pub reserved_blocks: usize, |
| 175 | /// `watermark_blocks` for a preempted head, 0 for a waiting head. |
| 176 | pub watermark_headroom: usize, |
| 177 | /// `needed_blocks + watermark_headroom`. |
| 178 | pub min_needed: usize, |
| 179 | /// `AienKvManager::total_block_count()`. |
| 180 | pub pool_blocks: usize, |
| 181 | pub verdict: AdmissionVerdict, |
| 182 | } |
| 183 | |
| 184 | /// Everything the scheduler looked at while deciding. |
| 185 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] |
| 186 | pub struct AdmitPreemptAlternatives { |
| 187 | /// `running_sequences` after `purge_stale_work`, before any preemption. |
| 188 | pub running_at_entry: Vec<SequenceId>, |
| 189 | /// `waiting_queue` after `purge_stale_work`, front first. |
| 190 | pub waiting_at_entry: Vec<SequenceId>, |
| 191 | /// `preempted_queue` after `purge_stale_work`, front first. |
| 192 | pub preempted_at_entry: Vec<SequenceId>, |
| 193 | /// Ranked victims when the pool was below the watermark; empty otherwise. |
| 194 | pub preemption_victims_considered: Vec<PreemptionVictim>, |
| 195 | pub running_examined: Vec<RunningItem>, |
| 196 | pub running_loop_stop: Option<LoopStop>, |
| 197 | pub admission_examined: Vec<AdmissionCandidate>, |
| 198 | } |
| 199 | |
| 200 | /// How `build_scheduled_batch` returned. |
| 201 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 202 | pub enum BatchOutcome { |
| 203 | Batch { |
| 204 | prefill_requests: usize, |
| 205 | decode_requests: usize, |
| 206 | /// Sum of prefill chunk lengths plus one per decode request, the same |
| 207 | /// quantity the scheduler compares against `max_batch_tokens`. |
| 208 | batch_tokens: usize, |
| 209 | }, |
| 210 | Empty, |
| 211 | Error(String), |
| 212 | } |
| 213 | |
| 214 | /// The production choice, copied from the batch the scheduler built. |
| 215 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 216 | pub struct AdmitPreemptChoice { |
| 217 | /// Victims actually preempted this step (at most one today). |
| 218 | pub preempted: Vec<SequenceId>, |
| 219 | /// `decode_requests` in batch order (running decodes, then fork admits). |
| 220 | pub decode_scheduled: Vec<SequenceId>, |
| 221 | /// `prefill_requests` in batch order with each chunk's token count. |
| 222 | pub prefill_scheduled: Vec<(SequenceId, usize)>, |
| 223 | /// Sequences the prefill gate sent back to the waiting queue head. |
| 224 | pub reprefill_requeued: Vec<SequenceId>, |
| 225 | pub outcome: BatchOutcome, |
| 226 | } |
| 227 | |
| 228 | /// One decision at `serve.admit_preempt`. Immutable once emitted. |
| 229 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 230 | pub struct AdmitPreemptRecord { |
| 231 | pub site: &'static str, |
| 232 | /// `AienScheduler::step_id` after this step's increment; equals the |
| 233 | /// `step_id` of the batch returned, when one was. |
| 234 | pub step_id: u64, |
| 235 | pub limits: BatchLimits, |
| 236 | /// `arena.active_count()` after purge, before the decision. |
| 237 | pub arena_active_at_entry: usize, |
| 238 | pub kv_at_entry: KvReading, |
| 239 | /// `available < watermark_blocks && !running.is_empty()`, the exact |
| 240 | /// predicate the watermark check evaluated. |
| 241 | pub below_watermark_at_entry: bool, |
| 242 | pub kv_at_exit: KvReading, |
| 243 | pub running_count_at_exit: usize, |
| 244 | pub waiting_count_at_exit: usize, |
| 245 | pub preempted_count_at_exit: usize, |
| 246 | pub alternatives: AdmitPreemptAlternatives, |
| 247 | pub choice: AdmitPreemptChoice, |
| 248 | } |
| 249 | |
| 250 | /// Read-only tap. The scheduler calls `observe_admit_preempt` once per |
| 251 | /// `build_scheduled_batch`, after the decision is final, with a shared |
| 252 | /// reference; the return type is `()`. Nothing an implementation does can |
| 253 | /// reach the scheduler's state. |
| 254 | pub trait DecisionObserver: Send + Sync { |
| 255 | fn observe_admit_preempt(&self, record: &AdmitPreemptRecord); |
| 256 | } |
| 257 | |
| 258 | /// Observer that keeps every record it is shown. Used by the parity tests |
| 259 | /// and the overhead benchmark; also a reasonable sink for recorded replays. |
| 260 | #[derive(Default)] |
| 261 | pub struct RecordingObserver { |
| 262 | records: Mutex<Vec<AdmitPreemptRecord>>, |
| 263 | } |
| 264 | |
| 265 | impl RecordingObserver { |
| 266 | pub fn new() -> Self { |
| 267 | Self::default() |
| 268 | } |
| 269 | |
| 270 | pub fn len(&self) -> usize { |
| 271 | self.records |
| 272 | .lock() |
| 273 | .expect("recording observer poisoned") |
| 274 | .len() |
| 275 | } |
| 276 | |
| 277 | pub fn is_empty(&self) -> bool { |
| 278 | self.len() == 0 |
| 279 | } |
| 280 | |
| 281 | /// Removes and returns every record seen so far. |
| 282 | pub fn take(&self) -> Vec<AdmitPreemptRecord> { |
| 283 | std::mem::take(&mut *self.records.lock().expect("recording observer poisoned")) |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | impl DecisionObserver for RecordingObserver { |
| 288 | fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { |
| 289 | self.records |
| 290 | .lock() |
| 291 | .expect("recording observer poisoned") |
| 292 | .push(record.clone()); |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// Observer that counts records and the serialized bytes they would occupy, |
| 297 | /// without storing them. Used by the overhead benchmark to separate the cost |
| 298 | /// of producing records from the cost of keeping them. |
| 299 | #[derive(Default)] |
| 300 | pub struct CountingObserver { |
| 301 | records: std::sync::atomic::AtomicU64, |
| 302 | bytes: std::sync::atomic::AtomicU64, |
| 303 | } |
| 304 | |
| 305 | impl CountingObserver { |
| 306 | pub fn new() -> Self { |
| 307 | Self::default() |
| 308 | } |
| 309 | |
| 310 | pub fn records(&self) -> u64 { |
| 311 | self.records.load(std::sync::atomic::Ordering::Relaxed) |
| 312 | } |
| 313 | |
| 314 | pub fn bytes(&self) -> u64 { |
| 315 | self.bytes.load(std::sync::atomic::Ordering::Relaxed) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | impl DecisionObserver for CountingObserver { |
| 320 | fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { |
| 321 | use std::sync::atomic::Ordering::Relaxed; |
| 322 | self.records.fetch_add(1, Relaxed); |
| 323 | let bytes = serde_json::to_vec(record).map(|v| v.len()).unwrap_or(0) as u64; |
| 324 | self.bytes.fetch_add(bytes, Relaxed); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | /// Per-step accumulator. Exists only while an observer is installed; every |
| 329 | /// `if let Some(trace)` in `build_scheduled_batch` is skipped otherwise. |
| 330 | #[derive(Debug, Default)] |
| 331 | pub(crate) struct AdmitPreemptTrace { |
| 332 | pub(crate) arena_active_at_entry: usize, |
| 333 | pub(crate) kv_at_entry: KvReading, |
| 334 | pub(crate) below_watermark_at_entry: bool, |
| 335 | pub(crate) alternatives: AdmitPreemptAlternatives, |
| 336 | pub(crate) preempted: Vec<SequenceId>, |
| 337 | pub(crate) decode_scheduled: Vec<SequenceId>, |
| 338 | pub(crate) prefill_scheduled: Vec<(SequenceId, usize)>, |
| 339 | pub(crate) reprefill_requeued: Vec<SequenceId>, |
| 340 | } |
| 341 | |
| 342 | impl AdmissionCandidate { |
| 343 | /// A queue head dropped before the KV manager was consulted; every |
| 344 | /// resource field is zero because the scheduler never computed one. |
| 345 | pub(crate) fn before_kv( |
| 346 | seq: SequenceId, |
| 347 | from_preempted_queue: bool, |
| 348 | verdict: AdmissionVerdict, |
| 349 | ) -> Self { |
| 350 | Self { |
| 351 | seq, |
| 352 | from_preempted_queue, |
| 353 | prompt_len: 0, |
| 354 | needed_blocks: 0, |
| 355 | free_blocks: 0, |
| 356 | reserved_blocks: 0, |
| 357 | watermark_headroom: 0, |
| 358 | min_needed: 0, |
| 359 | pool_blocks: 0, |
| 360 | verdict, |
| 361 | } |
| 362 | } |
| 363 | } |