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/patches/5ccb1926dc3effe7 # 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 ## GitHub aien-dev/aien-sovereign-core-mv#198 (code only) closed derived `5ccb1926dc3effe7` #198 Imported from GitHub aien-dev/aien-sovereign-core-mv#198 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `f571b9463672bfcb7aa956b63ea8ee318d80b718` · Head `4b4ca914b99205a4fddba693f4914fa1ef514d58` ### Apply it ``` git checkout -b patch-5ccb1926dc3effe7 f571b9463672bfcb7aa956b63ea8ee318d80b718 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/5ccb1926dc3effe7.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 198 4b4ca914b99205a4fddba693f4914fa1ef514d58 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":198,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/198","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:16Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 9a9d8897..b4bb4b9b 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:dfcfd805db0c30c667bc5682364bd3acb3383d494967dcae39f2420739723d7d", - "compiled_at": "2026-10-04T18:40:45Z", + "compiled_at": "2026-10-04T18:57:26Z", "compiler": "crumb-compile/1", - "digest": "sha256:47a1642c24a7359be52e869b405c8264bb335eec0faab538576a29176b4ab10e", + "digest": "sha256:21c2ec6095db6b30d3811be32c3bd148105fb2987dc3b81cfd2c6c0481be16e3", "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", - "files": 664, - "generated_at_commit": "82f723bdfe7ca1dd42ce716d65839dbe20a83e6c", - "source_tree": "sha256:efa1bea99a41833de3c580c46203442d75cc5ce977b6aa52493fa00cb66bda39" + "files": 671, + "generated_at_commit": "9d66c8f2d30bb7d770cb8e14282175cc7dfec043", + "source_tree": "sha256:baf4a50c75a7c7929708676ca137157178d0cd1898c183037ece666a25494c48" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index f8a85116..875116cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -286,11 +286,13 @@ dependencies = [ "aien-inference-abi", "aien-kv-cache", "aien-platform", + "async-trait", "futures-util", "parking_lot", "reqwest 0.12.28", "serde", "serde_json", + "sha2 0.10.9", "spark-max-rs", "tokio", ] diff --git a/crates/aien-scheduler/Cargo.toml b/crates/aien-scheduler/Cargo.toml index c123b232..f5c6a5b1 100644 --- a/crates/aien-scheduler/Cargo.toml +++ b/crates/aien-scheduler/Cargo.toml @@ -19,6 +19,10 @@ serde_json = "1.0" reqwest = { version = "0.12", features = ["json", "stream"] } futures-util = "0.3" +[dev-dependencies] +async-trait = "0.1" +sha2 = "0.10" + [[bin]] name = "bench_inference_stack" path = "src/bin/bench_inference_stack.rs" @@ -33,3 +37,8 @@ path = "src/bin/stress_aien_live.rs" # are decoded. The prefill-gate tests must FAIL with this feature on; see # scripts/prefill-gate/mutant.sh. prefill_mutant_no_check = [] +# MUTANT ONLY (DUAL serve.admit_preempt tap). Never enable in a real build. +# Makes an installed observer stop admission after one grant per step, so the +# decision differs with the tap on. tests/dual_observer_parity.rs must FAIL +# with this feature on (negative control for the read-only tap). +dual_observer_mutant_changes_decision = [] diff --git a/crates/aien-scheduler/src/dual_observer.rs b/crates/aien-scheduler/src/dual_observer.rs new file mode 100644 index 00000000..7b9d493f --- /dev/null +++ b/crates/aien-scheduler/src/dual_observer.rs @@ -0,0 +1,348 @@ +//! DUAL decision-site observer for `serve.admit_preempt` (ARCH-0031 §7.3, +//! DUAL-3 instrumentation). READ-ONLY by construction. +//! +//! `AienScheduler::build_scheduled_batch` is the one place in this crate that +//! decides admission, the preemption victim and the prefill chunk allocation. +//! This module lets a caller install a [`DecisionObserver`] that receives, +//! after each decision, one immutable [`AdmitPreemptRecord`] describing the +//! alternatives the scheduler actually looked at, the choice it made, and the +//! resource readings it made the choice with. +//! +//! What the tap cannot do: +//! +//! - It holds no reference to the scheduler, the KV manager or the arena. The +//! hook receives `&AdmitPreemptRecord` (a copy of already-made decisions) and +//! returns `()`. There is no return value the scheduler reads. +//! - With no observer installed (`None`, the default) every tracing branch is +//! skipped and the decision code runs exactly as before. The parity tests in +//! `tests/dual_decision_parity.rs` and `tests/dual_observer_parity.rs` hold +//! the serialized decisions byte-for-byte equal in both configurations. +//! - No field of a record is an authority input anywhere. A consumer that +//! reads one as a gate input fails its gate (ADR 0031 §6). +//! +//! The record names the production state machine's own identities +//! (`SequenceId`, step counter, KV block counts). It introduces no second +//! ledger: every number is copied from a local the scheduler computed for +//! its own decision, at the instant it computed it. +//! +//! ```compile_fail +//! // Negative control, held by the type system: an observer cannot change +//! // the record it is shown. `observe_admit_preempt` takes `&AdmitPreemptRecord`. +//! use aien_scheduler::dual_observer::{AdmitPreemptRecord, DecisionObserver}; +//! struct Tamper; +//! impl DecisionObserver for Tamper { +//! fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { +//! record.choice.preempted.clear(); +//! } +//! } +//! ``` +//! +//! ```compile_fail +//! // Negative control, held by the type system: the hook returns `()`, so an +//! // observer cannot hand a different choice back to the scheduler. +//! use aien_scheduler::dual_observer::{AdmitPreemptChoice, AdmitPreemptRecord, DecisionObserver}; +//! struct Override; +//! impl DecisionObserver for Override { +//! fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) -> AdmitPreemptChoice { +//! record.choice.clone() +//! } +//! } +//! ``` + +use crate::SequenceId; +use serde::Serialize; +use std::sync::Mutex; + +/// Registered decision-site id (DUAL_CURRENT_STATE §4). +pub const SERVE_ADMIT_PREEMPT_SITE: &str = "serve.admit_preempt"; + +/// Scheduler limits in force for the decision, copied from `SchedulerConfig`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct BatchLimits { + pub max_batch_size: usize, + pub max_batch_tokens: usize, + pub max_prefill_tokens: usize, + pub prefill_chunk_size: usize, + pub chunk_prefill: bool, + pub watermark_blocks: usize, +} + +/// KV pool reading. `free_blocks` is `AienKvManager::available_blocks`, +/// `total_blocks` is `total_block_count`, `active_tables` is +/// `active_sequence_count`. `allocated_blocks` is `total - free`, the same +/// arithmetic as `allocated_block_count`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub struct KvReading { + pub total_blocks: usize, + pub free_blocks: usize, + pub allocated_blocks: usize, + pub active_tables: usize, +} + +/// One running sequence the watermark check ranked as a preemption victim, +/// in the order the scheduler sorted them (lowest priority first; equal +/// priorities keep their `running_sequences` order, `sort_by_key` is stable). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct PreemptionVictim { + pub seq: SequenceId, + pub priority: u8, +} + +/// What step 2 of `build_scheduled_batch` did with one running sequence. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub enum RunningVerdict { + /// Arena has no record for the id (skipped). + NoRecord, + /// Prefilled, table ready: scheduled for one decode token. + Decode, + /// Prefilled flag set but the table was never computed: sent back to the + /// waiting queue head for a fresh prefill (PREFILL-GATE). + GateRefusedReprefill, + /// In-flight chunked prefill: this many prompt tokens scheduled now. + ContinuePrefill { chunk_len: usize }, + /// In-flight chunked prefill but no chunk fit (remaining or budget was 0). + ContinuePrefillNoChunk, + /// Prefilled sequence whose table is missing from the KV manager (skipped). + DecodeNoTable, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct RunningItem { + pub seq: SequenceId, + pub verdict: RunningVerdict, +} + +/// Why the running-sequence loop stopped before examining every running id. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum LoopStop { + BatchSizeReached, + BatchTokensReached, +} + +/// What step 3 of `build_scheduled_batch` did with one queue head. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub enum AdmissionVerdict { + /// Stale id at the queue head: dropped, loop continues. + StaleDropped, + /// Arena record missing: dropped, loop continues. + MissingRecord, + /// `available < min_needed` while something running could free blocks: + /// the sequence stays queued, loop stops. + WaitForBlocks, + /// `available < min_needed` and nothing can free blocks (or the need + /// exceeds the whole pool): `build_scheduled_batch` returned `Err`. + RefusedPoolExhausted, + /// Existing block table with computed K/V (a fork): entered decode + /// directly, reserving `needed_blocks` for its first copy-on-write. + AdmittedDecode, + /// Allocated `new_blocks` physical blocks and scheduled the first + /// `chunk_len` prompt tokens for prefill. + AdmittedPrefill { chunk_len: usize, new_blocks: usize }, + /// Prefill budget left no room for a first chunk: pushed back to its + /// queue head, loop stops. + ChunkBudgetExhausted, +} + +/// One queue head examined by the admission loop, with the exact numbers the +/// scheduler compared. Resource fields are zero for verdicts reached before +/// the KV manager was consulted (`StaleDropped`, `MissingRecord`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AdmissionCandidate { + pub seq: SequenceId, + pub from_preempted_queue: bool, + pub prompt_len: usize, + /// `AienKvManager::incremental_blocks_needed(seq, prompt_len)`. + pub needed_blocks: usize, + /// `AienKvManager::available_blocks()` at that instant. + pub free_blocks: usize, + /// Blocks promised to sequences admitted earlier in this same step. + pub reserved_blocks: usize, + /// `watermark_blocks` for a preempted head, 0 for a waiting head. + pub watermark_headroom: usize, + /// `needed_blocks + watermark_headroom`. + pub min_needed: usize, + /// `AienKvManager::total_block_count()`. + pub pool_blocks: usize, + pub verdict: AdmissionVerdict, +} + +/// Everything the scheduler looked at while deciding. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct AdmitPreemptAlternatives { + /// `running_sequences` after `purge_stale_work`, before any preemption. + pub running_at_entry: Vec, + /// `waiting_queue` after `purge_stale_work`, front first. + pub waiting_at_entry: Vec, + /// `preempted_queue` after `purge_stale_work`, front first. + pub preempted_at_entry: Vec, + /// Ranked victims when the pool was below the watermark; empty otherwise. + pub preemption_victims_considered: Vec, + pub running_examined: Vec, + pub running_loop_stop: Option, + pub admission_examined: Vec, +} + +/// How `build_scheduled_batch` returned. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub enum BatchOutcome { + Batch { + prefill_requests: usize, + decode_requests: usize, + /// Sum of prefill chunk lengths plus one per decode request, the same + /// quantity the scheduler compares against `max_batch_tokens`. + batch_tokens: usize, + }, + Empty, + Error(String), +} + +/// The production choice, copied from the batch the scheduler built. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AdmitPreemptChoice { + /// Victims actually preempted this step (at most one today). + pub preempted: Vec, + /// `decode_requests` in batch order (running decodes, then fork admits). + pub decode_scheduled: Vec, + /// `prefill_requests` in batch order with each chunk's token count. + pub prefill_scheduled: Vec<(SequenceId, usize)>, + /// Sequences the prefill gate sent back to the waiting queue head. + pub reprefill_requeued: Vec, + pub outcome: BatchOutcome, +} + +/// One decision at `serve.admit_preempt`. Immutable once emitted. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AdmitPreemptRecord { + pub site: &'static str, + /// `AienScheduler::step_id` after this step's increment; equals the + /// `step_id` of the batch returned, when one was. + pub step_id: u64, + pub limits: BatchLimits, + /// `arena.active_count()` after purge, before the decision. + pub arena_active_at_entry: usize, + pub kv_at_entry: KvReading, + /// `available < watermark_blocks && !running.is_empty()`, the exact + /// predicate the watermark check evaluated. + pub below_watermark_at_entry: bool, + pub kv_at_exit: KvReading, + pub running_count_at_exit: usize, + pub waiting_count_at_exit: usize, + pub preempted_count_at_exit: usize, + pub alternatives: AdmitPreemptAlternatives, + pub choice: AdmitPreemptChoice, +} + +/// Read-only tap. The scheduler calls `observe_admit_preempt` once per +/// `build_scheduled_batch`, after the decision is final, with a shared +/// reference; the return type is `()`. Nothing an implementation does can +/// reach the scheduler's state. +pub trait DecisionObserver: Send + Sync { + fn observe_admit_preempt(&self, record: &AdmitPreemptRecord); +} + +/// Observer that keeps every record it is shown. Used by the parity tests +/// and the overhead benchmark; also a reasonable sink for recorded replays. +#[derive(Default)] +pub struct RecordingObserver { + records: Mutex>, +} + +impl RecordingObserver { + pub fn new() -> Self { + Self::default() + } + + pub fn len(&self) -> usize { + self.records + .lock() + .expect("recording observer poisoned") + .len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Removes and returns every record seen so far. + pub fn take(&self) -> Vec { + std::mem::take(&mut *self.records.lock().expect("recording observer poisoned")) + } +} + +impl DecisionObserver for RecordingObserver { + fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { + self.records + .lock() + .expect("recording observer poisoned") + .push(record.clone()); + } +} + +/// Observer that counts records and the serialized bytes they would occupy, +/// without storing them. Used by the overhead benchmark to separate the cost +/// of producing records from the cost of keeping them. +#[derive(Default)] +pub struct CountingObserver { + records: std::sync::atomic::AtomicU64, + bytes: std::sync::atomic::AtomicU64, +} + +impl CountingObserver { + pub fn new() -> Self { + Self::default() + } + + pub fn records(&self) -> u64 { + self.records.load(std::sync::atomic::Ordering::Relaxed) + } + + pub fn bytes(&self) -> u64 { + self.bytes.load(std::sync::atomic::Ordering::Relaxed) + } +} + +impl DecisionObserver for CountingObserver { + fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { + use std::sync::atomic::Ordering::Relaxed; + self.records.fetch_add(1, Relaxed); + let bytes = serde_json::to_vec(record).map(|v| v.len()).unwrap_or(0) as u64; + self.bytes.fetch_add(bytes, Relaxed); + } +} + +/// Per-step accumulator. Exists only while an observer is installed; every +/// `if let Some(trace)` in `build_scheduled_batch` is skipped otherwise. +#[derive(Debug, Default)] +pub(crate) struct AdmitPreemptTrace { + pub(crate) arena_active_at_entry: usize, + pub(crate) kv_at_entry: KvReading, + pub(crate) below_watermark_at_entry: bool, + pub(crate) alternatives: AdmitPreemptAlternatives, + pub(crate) preempted: Vec, + pub(crate) decode_scheduled: Vec, + pub(crate) prefill_scheduled: Vec<(SequenceId, usize)>, + pub(crate) reprefill_requeued: Vec, +} + +impl AdmissionCandidate { + /// A queue head dropped before the KV manager was consulted; every + /// resource field is zero because the scheduler never computed one. + pub(crate) fn before_kv( + seq: SequenceId, + from_preempted_queue: bool, + verdict: AdmissionVerdict, + ) -> Self { + Self { + seq, + from_preempted_queue, + prompt_len: 0, + needed_blocks: 0, + free_blocks: 0, + reserved_blocks: 0, + watermark_headroom: 0, + min_needed: 0, + pool_blocks: 0, + verdict, + } + } +} diff --git a/crates/aien-scheduler/src/lib.rs b/crates/aien-scheduler/src/lib.rs index 37830b5c..654ad22c 100644 --- a/crates/aien-scheduler/src/lib.rs +++ b/crates/aien-scheduler/src/lib.rs @@ -1,8 +1,14 @@ #![allow(clippy::too_many_arguments)] +pub mod dual_observer; pub mod sequence; pub use sequence::*; +use crate::dual_observer::{ + AdmissionCandidate, AdmissionVerdict, AdmitPreemptAlternatives, AdmitPreemptChoice, + AdmitPreemptRecord, AdmitPreemptTrace, BatchLimits, BatchOutcome, DecisionObserver, KvReading, + LoopStop, PreemptionVictim, RunningItem, RunningVerdict, SERVE_ADMIT_PREEMPT_SITE, +}; use aien_abi_core::{ AienInferenceBackend, DecodeOutput, FinishReason, ScheduledBatch, SequenceRequest, StepMetrics, }; @@ -75,6 +81,9 @@ pub struct AienScheduler { running_sequences: Vec, step_id: u64, metrics: SchedulerMetrics, + /// DUAL `serve.admit_preempt` read-only tap. `None` (the default) skips + /// every tracing branch in `build_scheduled_batch`. + observer: Option>, } impl AienScheduler { @@ -89,9 +98,21 @@ impl AienScheduler { running_sequences: Vec::new(), step_id: 0, metrics: SchedulerMetrics::default(), + observer: None, } } + /// Installs (or with `None` removes) the DUAL `serve.admit_preempt` + /// observer. The observer is shown each decision after it is final and + /// cannot change it (see `dual_observer`). + pub fn set_decision_observer(&mut self, observer: Option>) { + self.observer = observer; + } + + pub fn decision_observer_installed(&self) -> bool { + self.observer.is_some() + } + pub fn config(&self) -> &SchedulerConfig { &self.config } @@ -337,11 +358,92 @@ impl AienScheduler { self.running_sequences.retain(|&id| !arena.is_stale(id)); } + fn kv_reading(&self) -> KvReading { + let kv = self.kv_manager.read(); + let total_blocks = kv.total_block_count(); + let free_blocks = kv.available_blocks(); + KvReading { + total_blocks, + free_blocks, + allocated_blocks: total_blocks - free_blocks, + active_tables: kv.active_sequence_count(), + } + } + /// Builds the next scheduled batch enforcing chunked prefill budgets and watermark preemption. + /// + /// DUAL `serve.admit_preempt`: when an observer is installed, the decision + /// is traced while it is made and one `AdmitPreemptRecord` is handed to the + /// observer after it is final. Without an observer no trace exists and the + /// decision code path is the same as before the tap. pub fn build_scheduled_batch(&mut self) -> Result, String> { + let mut trace = self.observer.is_some().then(AdmitPreemptTrace::default); + let result = self.build_scheduled_batch_traced(&mut trace); + if let (Some(observer), Some(trace)) = (self.observer.clone(), trace) { + let outcome = match &result { + Ok(Some(batch)) => BatchOutcome::Batch { + prefill_requests: batch.prefill_requests.len(), + decode_requests: batch.decode_requests.len(), + batch_tokens: batch + .prefill_requests + .iter() + .map(|r| r.prompt_tokens.len()) + .sum::() + + batch.decode_requests.len(), + }, + Ok(None) => BatchOutcome::Empty, + Err(e) => BatchOutcome::Error(e.clone()), + }; + let record = AdmitPreemptRecord { + site: SERVE_ADMIT_PREEMPT_SITE, + step_id: self.step_id, + limits: BatchLimits { + max_batch_size: self.config.max_batch_size, + max_batch_tokens: self.config.max_batch_tokens, + max_prefill_tokens: self.config.max_prefill_tokens, + prefill_chunk_size: self.config.prefill_chunk_size, + chunk_prefill: self.config.chunk_prefill, + watermark_blocks: self.config.watermark_blocks, + }, + arena_active_at_entry: trace.arena_active_at_entry, + kv_at_entry: trace.kv_at_entry, + below_watermark_at_entry: trace.below_watermark_at_entry, + kv_at_exit: self.kv_reading(), + running_count_at_exit: self.running_sequences.len(), + waiting_count_at_exit: self.waiting_queue.len(), + preempted_count_at_exit: self.preempted_queue.len(), + alternatives: trace.alternatives, + choice: AdmitPreemptChoice { + preempted: trace.preempted, + decode_scheduled: trace.decode_scheduled, + prefill_scheduled: trace.prefill_scheduled, + reprefill_requeued: trace.reprefill_requeued, + outcome, + }, + }; + observer.observe_admit_preempt(&record); + } + result + } + + fn build_scheduled_batch_traced( + &mut self, + trace: &mut Option, + ) -> Result, String> { self.step_id += 1; self.purge_stale_work(); + if let Some(t) = trace.as_mut() { + t.arena_active_at_entry = self.arena.active_count(); + t.kv_at_entry = self.kv_reading(); + t.alternatives = AdmitPreemptAlternatives { + running_at_entry: self.running_sequences.clone(), + waiting_at_entry: self.waiting_queue.iter().copied().collect(), + preempted_at_entry: self.preempted_queue.iter().copied().collect(), + ..AdmitPreemptAlternatives::default() + }; + } + let mut prefill_requests = Vec::new(); let mut decode_requests = Vec::new(); let mut block_tables = HashMap::new(); @@ -357,6 +459,10 @@ impl AienScheduler { { let kv = self.kv_manager.read(); let available = kv.available_blocks(); + if let Some(t) = trace.as_mut() { + t.below_watermark_at_entry = + available < self.config.watermark_blocks && !self.running_sequences.is_empty(); + } if available < self.config.watermark_blocks && !self.running_sequences.is_empty() { let mut candidates: Vec<(SequenceId, Priority)> = self .running_sequences @@ -364,12 +470,24 @@ impl AienScheduler { .filter_map(|&id| self.arena.get(id).map(|rec| (id, rec.priority))) .collect(); candidates.sort_by_key(|c| c.1 as u8); + if let Some(t) = trace.as_mut() { + t.alternatives.preemption_victims_considered = candidates + .iter() + .map(|&(seq, p)| PreemptionVictim { + seq, + priority: p as u8, + }) + .collect(); + } if let Some((preempt_id, _)) = candidates.first() { let preempt_id = *preempt_id; drop(kv); if let Some(pos) = self.running_sequences.iter().position(|&x| x == preempt_id) { + if let Some(t) = trace.as_mut() { + t.preempted.push(preempt_id); + } self.running_sequences.remove(pos); let _ = self.kv_manager.write().free_sequence(preempt_id.to_u64()); if let Some(rec) = self.arena.get_mut(preempt_id) { @@ -392,15 +510,29 @@ impl AienScheduler { for seq_id in running_ids { if decode_requests.len() + prefill_requests.len() >= self.config.max_batch_size { + if let Some(t) = trace.as_mut() { + t.alternatives.running_loop_stop = Some(LoopStop::BatchSizeReached); + } break; } if current_tokens >= self.config.max_batch_tokens { + if let Some(t) = trace.as_mut() { + t.alternatives.running_loop_stop = Some(LoopStop::BatchTokensReached); + } break; } let seq = match self.arena.get_mut(seq_id) { Some(s) => s, - None => continue, + None => { + if let Some(t) = trace.as_mut() { + t.alternatives.running_examined.push(RunningItem { + seq: seq_id, + verdict: RunningVerdict::NoRecord, + }); + } + continue; + } }; if seq.is_prefilled { @@ -410,11 +542,13 @@ impl AienScheduler { .read() .get_block_table(seq_id.to_u64()) .map(|t| (t.block_ids.clone(), t.is_prefill_ready())); + let mut verdict = RunningVerdict::DecodeNoTable; if let Some((blocks, ready)) = table_state { if prefill_gate_allows_decode(ready) { block_tables.insert(seq_id.to_u64(), blocks); decode_requests.push(seq_id.to_u64()); current_tokens += 1; + verdict = RunningVerdict::Decode; } else { // The table exists but its K/V was never computed: // send the sequence back for a real prefill, never decode. @@ -422,7 +556,17 @@ impl AienScheduler { seq.prompt_tokens_prefilled = 0; seq.phase = SequencePhase::Waiting; needs_prefill.push(seq_id); + verdict = RunningVerdict::GateRefusedReprefill; + } + } + if let Some(t) = trace.as_mut() { + if verdict == RunningVerdict::Decode { + t.decode_scheduled.push(seq_id); } + t.alternatives.running_examined.push(RunningItem { + seq: seq_id, + verdict, + }); } } else { // Continuing chunked prefill @@ -452,12 +596,29 @@ impl AienScheduler { current_tokens += chunk_size; prefill_budget = prefill_budget.saturating_sub(chunk_size); } + if let Some(t) = trace.as_mut() { + let verdict = if chunk_size > 0 { + t.prefill_scheduled.push((seq_id, chunk_size)); + RunningVerdict::ContinuePrefill { + chunk_len: chunk_size, + } + } else { + RunningVerdict::ContinuePrefillNoChunk + }; + t.alternatives.running_examined.push(RunningItem { + seq: seq_id, + verdict, + }); + } } } // Sequences refused decode by the prefill gate: drop the uncomputed // (possibly shared) table and requeue at the front for a fresh prefill. for seq_id in needs_prefill { + if let Some(t) = trace.as_mut() { + t.reprefill_requeued.push(seq_id); + } self.running_sequences.retain(|&x| x != seq_id); let _ = self.kv_manager.write().free_sequence(seq_id.to_u64()); self.waiting_queue.push_front(seq_id); @@ -478,6 +639,15 @@ impl AienScheduler { }; if self.arena.is_stale(next_seq_id) { + if let Some(t) = trace.as_mut() { + t.alternatives + .admission_examined + .push(AdmissionCandidate::before_kv( + next_seq_id, + is_preempted, + AdmissionVerdict::StaleDropped, + )); + } if is_preempted { self.preempted_queue.pop_front(); } else { @@ -489,6 +659,15 @@ impl AienScheduler { let prompt_len = match self.arena.get(next_seq_id) { Some(s) => s.prompt.len(), None => { + if let Some(t) = trace.as_mut() { + t.alternatives + .admission_examined + .push(AdmissionCandidate::before_kv( + next_seq_id, + is_preempted, + AdmissionVerdict::MissingRecord, + )); + } if is_preempted { self.preempted_queue.pop_front(); } else { @@ -522,6 +701,28 @@ impl AienScheduler { }; let min_needed = needed_blocks + watermark_headroom; + // DUAL tap: one AdmissionCandidate per queue head examined, with + // the exact numbers compared above. Expands to nothing when no + // observer is installed (`trace` is None). + macro_rules! trace_admission { + ($verdict:expr) => { + if let Some(t) = trace.as_mut() { + t.alternatives.admission_examined.push(AdmissionCandidate { + seq: next_seq_id, + from_preempted_queue: is_preempted, + prompt_len, + needed_blocks, + free_blocks, + reserved_blocks, + watermark_headroom, + min_needed, + pool_blocks, + verdict: $verdict, + }); + } + }; + } + if available < min_needed { // Waiting is only honest while something can still free blocks. // A request larger than the whole pool, or one that waits with @@ -530,6 +731,7 @@ impl AienScheduler { && decode_requests.is_empty() && prefill_requests.is_empty(); if min_needed > pool_blocks || nothing_can_free { + trace_admission!(AdmissionVerdict::RefusedPoolExhausted); return Err(format!( "{KV_POOL_EXHAUSTED_PREFIX} admission of sequence {} needs {} new KV \ blocks (plus {} watermark) but only {} are free ({} in the pool) and \ @@ -541,6 +743,7 @@ impl AienScheduler { pool_blocks, )); } + trace_admission!(AdmissionVerdict::WaitForBlocks); break; } @@ -580,8 +783,20 @@ impl AienScheduler { seq.prompt_tokens_prefilled = prompt_len; decode_requests.push(next_seq_id.to_u64()); current_tokens += 1; + trace_admission!(AdmissionVerdict::AdmittedDecode); + if let Some(t) = trace.as_mut() { + t.decode_scheduled.push(next_seq_id); + } reserved_blocks += needed_blocks; self.running_sequences.push(next_seq_id); + // MUTANT ONLY (feature `dual_observer_mutant_changes_decision`): + // an observer's presence stops admission after one grant. + // The parity tests must FAIL with this feature on. + if cfg!(feature = "dual_observer_mutant_changes_decision") + && trace.is_some() + { + break; + } continue; } Some(_) => { @@ -593,6 +808,7 @@ impl AienScheduler { } if chunk_size == 0 { + trace_admission!(AdmissionVerdict::ChunkBudgetExhausted); if is_preempted { self.preempted_queue.push_front(next_seq_id); } else { @@ -611,6 +827,7 @@ impl AienScheduler { .mark_prefill_pending(next_seq_id.to_u64()) .map_err(|e| e.to_string())?; + let new_blocks = assigned_blocks.len(); block_tables.insert(next_seq_id.to_u64(), assigned_blocks); let chunk_tokens = seq.prompt[0..chunk_size].to_vec(); @@ -628,6 +845,18 @@ impl AienScheduler { seq.phase = SequencePhase::Prefill; self.running_sequences.push(next_seq_id); + trace_admission!(AdmissionVerdict::AdmittedPrefill { + chunk_len: chunk_size, + new_blocks, + }); + if let Some(t) = trace.as_mut() { + t.prefill_scheduled.push((next_seq_id, chunk_size)); + } + // MUTANT ONLY (feature `dual_observer_mutant_changes_decision`), + // see the decode admission above. + if cfg!(feature = "dual_observer_mutant_changes_decision") && trace.is_some() { + break; + } } } diff --git a/crates/aien-scheduler/tests/dual_common/mod.rs b/crates/aien-scheduler/tests/dual_common/mod.rs new file mode 100644 index 00000000..224a8acb --- /dev/null +++ b/crates/aien-scheduler/tests/dual_common/mod.rs @@ -0,0 +1,686 @@ +//! Deterministic `serve.admit_preempt` workloads and a canonical, serializable +//! trace of every decision they produce (DUAL-3a instrumentation, ADR 0031). +//! +//! Everything here uses only APIs that exist on `main` before the observer +//! landed, so `dual_decision_golden.rs` compiles and runs on the base commit +//! and the golden fixture can be produced there. The observer tests reuse +//! the same workloads and compare traces produced with and without a tap. +//! +//! Determinism: `MockInferenceBackend` emits fixed tokens, never sleeps +//! (`simulated_step_latency_us` only adds to a reported figure), and every +//! timing field is excluded from the trace. + +#![allow(dead_code)] + +use aien_abi_core::{ + AienInferenceBackend, DecodeOutput, ModelConfig, SamplingParams, ScheduledBatch, + SequenceRequest, StepMetrics, +}; +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::{create_shared_kv_manager, KvMetrics, SharedKvManager}; +use aien_scheduler::{AienScheduler, SchedulerConfig, SequenceId}; +use async_trait::async_trait; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Backend wrapper that keeps a copy of every `ScheduledBatch` the scheduler +/// handed it. The batch is the production decision; the wrapper changes +/// nothing about how the mock answers. +pub struct BatchRecordingBackend { + inner: MockInferenceBackend, + pub batches: Vec, +} + +impl BatchRecordingBackend { + pub fn new() -> Self { + Self { + inner: MockInferenceBackend::new(0), + batches: Vec::new(), + } + } +} + +impl Default for BatchRecordingBackend { + fn default() -> Self { + Self::new() + } +} + +#[async_trait] +impl AienInferenceBackend for BatchRecordingBackend { + async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> { + self.inner.load_model(config).await + } + + async fn execute_step( + &mut self, + batch: &ScheduledBatch, + ) -> Result<(Vec, StepMetrics), String> { + self.batches.push(batch.clone()); + self.inner.execute_step(batch).await + } + + fn manages_kv_cache(&self) -> bool { + self.inner.manages_kv_cache() + } +} + +/// One action of a scripted workload. +#[derive(Debug, Clone)] +pub enum Action { + /// `submit_request` with an explicit `request_id` (slot in the high 32 + /// bits, generation 1) so the KV id is known to the script. + Submit { + slot: u32, + prompt_len: usize, + priority: u8, + max_tokens: usize, + }, + /// KV-level `fork_prefilled(parent, child)` for each child slot, then + /// `submit_request` for the child with the same prompt as the parent: + /// the scheduler must admit it straight into decode on its existing table. + ForkPrefilled { + parent_slot: u32, + child_slots: Vec, + prompt_len: usize, + max_tokens: usize, + }, + /// `scheduler.step` this many times. An `Err` is recorded and the loop + /// goes on (the request stays queued, as production does). + Step(usize), + /// `scheduler.step` until waiting, preempted and running are all empty or + /// `max` steps ran, whichever comes first. + Drain { max: usize }, +} + +#[derive(Debug, Clone)] +pub struct Scenario { + pub name: &'static str, + pub kv_blocks: usize, + pub block_size: usize, + pub config: SchedulerConfig, + pub actions: Vec, + /// When true the scenario is expected to end with nothing queued, nothing + /// running and zero KV blocks held (the leak check applies). + pub expect_drained: bool, +} + +pub fn seq(slot: u32) -> SequenceId { + SequenceId::new(slot, 1).expect("generation 1 is valid") +} + +pub fn request(slot: u32, prompt_len: usize, priority: u8, max_tokens: usize) -> SequenceRequest { + SequenceRequest { + request_id: seq(slot).to_u64(), + prompt_tokens: (0..prompt_len as u32).map(|t| 1000 + t).collect(), + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens, + stop_token_ids: vec![], + }, + arrival_time_ns: 0, + priority, + } +} + +/// Canonical form of a batch: `block_tables` sorted by sequence id so two +/// equal decisions serialize to equal bytes (`HashMap` order is not stable). +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct CanonBatch { + pub step_id: u64, + pub prefill: Vec<(u64, Vec, u8)>, + pub decode: Vec, + pub block_tables: BTreeMap>, +} + +impl CanonBatch { + pub fn from(batch: &ScheduledBatch) -> Self { + Self { + step_id: batch.step_id, + prefill: batch + .prefill_requests + .iter() + .map(|r| (r.request_id, r.prompt_tokens.clone(), r.priority)) + .collect(), + decode: batch.decode_requests.clone(), + block_tables: batch + .block_tables + .iter() + .map(|(k, v)| (*k, v.clone())) + .collect(), + } + } +} + +/// KV accounting as the manager reports it, read after each step. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct KvState { + pub total_blocks: usize, + pub free_blocks: usize, + pub allocated_blocks: usize, + pub active_tables: usize, + pub physical_pages: usize, + pub logical_pages: usize, + pub shared_pages: usize, + pub private_pages: usize, + pub cow_faults: usize, + pub used_blocks: usize, + /// `(block id, ref_count, is_shared)` for every block with ref_count > 0. + pub active_blocks: Vec<(usize, usize, bool)>, +} + +impl KvState { + pub fn read(kv: &SharedKvManager) -> Self { + let kv = kv.read(); + let m: KvMetrics = kv.metrics(); + Self { + total_blocks: kv.total_block_count(), + free_blocks: kv.available_blocks(), + allocated_blocks: kv.allocated_block_count(), + active_tables: kv.active_sequence_count(), + physical_pages: m.physical_pages, + logical_pages: m.logical_pages, + shared_pages: m.shared_pages, + private_pages: m.private_pages, + cow_faults: m.cow_faults, + used_blocks: m.used_blocks, + active_blocks: kv.debug_active_blocks(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct SchedulerState { + pub waiting: usize, + pub preempted: usize, + pub running: usize, + pub arena_active: usize, + pub total_steps: u64, + pub admitted_requests: u64, + pub finished_requests: u64, + pub preempted_requests: u64, + pub total_prefill_tokens: u64, + pub total_decode_tokens: u64, + pub chunked_prefill_steps: u64, +} + +impl SchedulerState { + pub fn read(s: &AienScheduler) -> Self { + let m = s.metrics(); + Self { + waiting: s.waiting_count(), + preempted: s.preempted_count(), + running: s.running_count(), + arena_active: s.arena().active_count(), + total_steps: m.total_steps, + admitted_requests: m.admitted_requests, + finished_requests: m.finished_requests, + preempted_requests: m.preempted_requests, + total_prefill_tokens: m.total_prefill_tokens, + total_decode_tokens: m.total_decode_tokens, + chunked_prefill_steps: m.chunked_prefill_steps, + } + } +} + +/// Everything observable about one `scheduler.step`, timing excluded. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct StepTrace { + pub index: usize, + /// The batch the scheduler handed the backend (`None` when the step + /// returned `Ok(None)` or `Err`). + pub batch: Option, + pub error: Option, + pub outputs: Vec, + pub prefill_tokens_processed: Option, + pub decode_tokens_emitted: Option, + pub active_kv_blocks: Option, + pub kv: KvState, + pub scheduler: SchedulerState, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ScenarioTrace { + pub name: String, + pub steps: Vec, + /// Number of `scheduler.step` calls, each of which is exactly one + /// `build_scheduled_batch` decision. + pub decisions: usize, + pub final_kv: KvState, + pub final_scheduler: SchedulerState, +} + +/// Builds the scheduler and KV manager for a scenario. The caller may install +/// an observer on the scheduler before running. +pub fn build(scenario: &Scenario) -> (AienScheduler, SharedKvManager) { + let kv = create_shared_kv_manager(scenario.kv_blocks, scenario.block_size); + let scheduler = AienScheduler::new(scenario.config.clone(), kv.clone()); + (scheduler, kv) +} + +/// Runs the scenario's actions on a prepared scheduler and returns the trace. +pub fn run( + scenario: &Scenario, + scheduler: &mut AienScheduler, + kv: &SharedKvManager, +) -> ScenarioTrace { + let rt = tokio::runtime::Builder::new_current_thread() + .build() + .expect("tokio current-thread runtime"); + let mut backend = BatchRecordingBackend::new(); + let mut steps: Vec = Vec::new(); + + let mut one_step = |scheduler: &mut AienScheduler, backend: &mut BatchRecordingBackend| { + let before = backend.batches.len(); + let result = rt.block_on(scheduler.step(backend)); + let batch = if backend.batches.len() > before { + Some(CanonBatch::from(&backend.batches[before])) + } else { + None + }; + let (error, outputs, pm, dm, akb) = match &result { + Ok(Some((outputs, metrics))) => ( + None, + outputs.iter().map(|o| format!("{o:?}")).collect(), + Some(metrics.prefill_tokens_processed), + Some(metrics.decode_tokens_emitted), + Some(metrics.active_kv_blocks), + ), + Ok(None) => (None, Vec::new(), None, None, None), + Err(e) => (Some(e.clone()), Vec::new(), None, None, None), + }; + steps.push(StepTrace { + index: steps.len(), + batch, + error, + outputs, + prefill_tokens_processed: pm, + decode_tokens_emitted: dm, + active_kv_blocks: akb, + kv: KvState::read(kv), + scheduler: SchedulerState::read(scheduler), + }); + }; + + for action in &scenario.actions { + match action { + Action::Submit { + slot, + prompt_len, + priority, + max_tokens, + } => { + scheduler.submit_request(request(*slot, *prompt_len, *priority, *max_tokens)); + } + Action::ForkPrefilled { + parent_slot, + child_slots, + prompt_len, + max_tokens, + } => { + for child in child_slots { + kv.write() + .fork_prefilled(seq(*parent_slot).to_u64(), seq(*child).to_u64()) + .expect("fork_prefilled of a ready parent"); + scheduler.submit_request(request(*child, *prompt_len, 1, *max_tokens)); + } + } + Action::Step(n) => { + for _ in 0..*n { + one_step(scheduler, &mut backend); + } + } + Action::Drain { max } => { + let mut ran = 0; + while ran < *max + && (scheduler.waiting_count() > 0 + || scheduler.running_count() > 0 + || scheduler.preempted_count() > 0) + { + one_step(scheduler, &mut backend); + ran += 1; + } + } + } + } + + let decisions = steps.len(); + ScenarioTrace { + name: scenario.name.to_string(), + steps, + decisions, + final_kv: KvState::read(kv), + final_scheduler: SchedulerState::read(scheduler), + } +} + +fn cfg( + max_batch_size: usize, + max_batch_tokens: usize, + max_prefill_tokens: usize, + prefill_chunk_size: usize, + chunk_prefill: bool, + watermark_blocks: usize, +) -> SchedulerConfig { + SchedulerConfig { + max_batch_size, + max_batch_tokens, + max_prefill_tokens, + prefill_chunk_size, + chunk_prefill, + watermark_blocks, + } +} + +/// The pre-registered workload set. Names are stable: the golden fixture and +/// the receipts refer to them. +#[allow(clippy::vec_init_then_push)] +pub fn scenarios() -> Vec { + let mut v = Vec::new(); + + // Admission: four short requests fit the batch and the pool; they run to + // their length limit and the pool returns to empty. + v.push(Scenario { + name: "admission_basic", + kv_blocks: 64, + block_size: 16, + config: cfg(8, 1024, 512, 128, true, 2), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 20, + priority: 1, + max_tokens: 3, + }, + Action::Submit { + slot: 2, + prompt_len: 7, + priority: 2, + max_tokens: 2, + }, + Action::Submit { + slot: 3, + prompt_len: 33, + priority: 0, + max_tokens: 4, + }, + Action::Submit { + slot: 4, + prompt_len: 16, + priority: 3, + max_tokens: 1, + }, + Action::Drain { max: 32 }, + ], + expect_drained: true, + }); + + // No admission: nothing queued, the step must return Ok(None) and touch + // nothing. + v.push(Scenario { + name: "no_admission_empty_queues", + kv_blocks: 16, + block_size: 16, + config: cfg(8, 1024, 512, 128, true, 2), + actions: vec![Action::Step(3)], + expect_drained: true, + }); + + // Chunked prefill: a 300-token prompt with a 64-token chunk and a + // 100-token prefill budget per step spreads over several steps while a + // second sequence decodes beside it. + v.push(Scenario { + name: "chunked_prefill_continuation", + kv_blocks: 64, + block_size: 16, + config: cfg(8, 1024, 100, 64, true, 2), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 10, + priority: 1, + max_tokens: 6, + }, + Action::Step(1), + Action::Submit { + slot: 2, + prompt_len: 300, + priority: 1, + max_tokens: 2, + }, + Action::Drain { max: 40 }, + ], + expect_drained: true, + }); + + // Preemption: 6-block pool, watermark 3, two 32-token prompts (2 blocks + // each). After admission 2 blocks are free (< 3): the lower-priority + // sequence is preempted on the next step, then readmitted later. + v.push(Scenario { + name: "preemption_watermark", + kv_blocks: 6, + block_size: 16, + config: cfg(4, 1024, 512, 128, false, 3), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 32, + priority: 3, + max_tokens: 4, + }, + Action::Submit { + slot: 2, + prompt_len: 32, + priority: 1, + max_tokens: 4, + }, + Action::Drain { max: 40 }, + ], + expect_drained: true, + }); + + // Ties: same pool pressure, equal priorities. `sort_by_key` is stable, so + // the victim is the first in `running_sequences` order. + v.push(Scenario { + name: "preemption_tie_equal_priority", + kv_blocks: 6, + block_size: 16, + config: cfg(4, 1024, 512, 128, false, 3), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 32, + priority: 1, + max_tokens: 4, + }, + Action::Submit { + slot: 2, + prompt_len: 32, + priority: 1, + max_tokens: 4, + }, + Action::Drain { max: 40 }, + ], + expect_drained: true, + }); + + // No preemption under sufficient resources: a large pool, the same two + // requests, no victim is ever ranked. + v.push(Scenario { + name: "no_preemption_sufficient_pool", + kv_blocks: 256, + block_size: 16, + config: cfg(4, 1024, 512, 128, false, 3), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 32, + priority: 3, + max_tokens: 4, + }, + Action::Submit { + slot: 2, + prompt_len: 32, + priority: 1, + max_tokens: 4, + }, + Action::Drain { max: 40 }, + ], + expect_drained: true, + }); + + // Queue exhaustion: twelve requests against a batch of 4. The admission + // loop stops on the batch-size limit every step until the queue empties. + let mut actions: Vec = (1..=12) + .map(|slot| Action::Submit { + slot, + prompt_len: 8 + slot as usize, + priority: (slot % 4) as u8, + max_tokens: 2, + }) + .collect(); + actions.push(Action::Drain { max: 64 }); + v.push(Scenario { + name: "queue_exhaustion_batch_limit", + kv_blocks: 128, + block_size: 16, + config: cfg(4, 1024, 512, 128, true, 1), + actions, + expect_drained: true, + }); + + // Capacity boundary, one below: 8-block pool, a prompt needing 7 blocks. + v.push(Scenario { + name: "capacity_one_below", + kv_blocks: 8, + block_size: 16, + config: cfg(4, 4096, 4096, 4096, true, 0), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 7 * 16, + priority: 1, + max_tokens: 1, + }, + Action::Drain { max: 8 }, + ], + expect_drained: true, + }); + + // Capacity boundary, exactly at: a prompt needing all 8 blocks. + v.push(Scenario { + name: "capacity_exactly_at", + kv_blocks: 8, + block_size: 16, + config: cfg(4, 4096, 4096, 4096, true, 0), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 8 * 16, + priority: 1, + max_tokens: 1, + }, + Action::Drain { max: 8 }, + ], + expect_drained: true, + }); + + // Capacity boundary, one above: 9 blocks needed from an 8-block pool with + // nothing running. The step returns the KV_POOL_EXHAUSTED error and the + // request stays queued; nothing is allocated. + v.push(Scenario { + name: "capacity_one_above_refused", + kv_blocks: 8, + block_size: 16, + config: cfg(4, 4096, 4096, 4096, true, 0), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 9 * 16, + priority: 1, + max_tokens: 1, + }, + Action::Step(2), + ], + expect_drained: false, + }); + + // Shortfall while something runs: the second request waits (no error) + // until the first finishes and frees its blocks. + v.push(Scenario { + name: "capacity_wait_while_running", + kv_blocks: 8, + block_size: 16, + config: cfg(4, 4096, 4096, 4096, true, 0), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 5 * 16, + priority: 1, + max_tokens: 2, + }, + Action::Step(1), + Action::Submit { + slot: 2, + prompt_len: 4 * 16, + priority: 1, + max_tokens: 1, + }, + Action::Drain { max: 16 }, + ], + expect_drained: true, + }); + + v.push(fanout(32)); + v.push(fanout(500)); + v +} + +/// Branch fan-out: a 64-token parent is prefilled (2 steps), then `n` +/// children share its blocks via `fork_prefilled` and are admitted straight +/// into decode on their existing tables, each reserving its copy-on-write +/// block. The parent and every child run to their length limit. +pub fn fanout(n: u32) -> Scenario { + let name: &'static str = match n { + 32 => "fanout_32_way", + 500 => "fanout_500_way", + _ => "fanout_custom", + }; + Scenario { + name, + kv_blocks: 4096, + block_size: 16, + config: cfg(1024, 16384, 4096, 512, true, 8), + actions: vec![ + Action::Submit { + slot: 1, + prompt_len: 64, + priority: 1, + max_tokens: 2, + }, + Action::Step(1), + Action::ForkPrefilled { + parent_slot: 1, + child_slots: (2..2 + n).collect(), + prompt_len: 64, + max_tokens: 3, + }, + Action::Drain { max: 64 }, + ], + expect_drained: true, + } +} + +pub fn scenario(name: &str) -> Scenario { + scenarios() + .into_iter() + .find(|s| s.name == name) + .unwrap_or_else(|| panic!("no scenario named {name}")) +} + +/// Canonical JSON (serde_json preserves struct field order; maps are +/// `BTreeMap`), the bytes the parity tests compare. +pub fn canonical_json(value: &T) -> Vec { + serde_json::to_vec(value).expect("trace serializes") +} diff --git a/crates/aien-scheduler/tests/dual_decision_golden.rs b/crates/aien-scheduler/tests/dual_decision_golden.rs new file mode 100644 index 00000000..cb802611 --- /dev/null +++ b/crates/aien-scheduler/tests/dual_decision_golden.rs @@ -0,0 +1,116 @@ +//! Before/after proof for the `serve.admit_preempt` tap (DUAL-3a). +//! +//! `build_scheduled_batch` was split into a thin wrapper and a traced body so +//! an observer can be shown the decision. This test uses only APIs that exist +//! on `main` before that change: it runs the pre-registered workload set with +//! no observer and compares the sha256 of the canonical trace of every +//! decision, per scenario, against +//! `tests/fixtures/dual_serve_admit_preempt.golden.json`. +//! +//! The fixture was produced on the base commit (recorded in the evidence +//! receipt) by running this same file there with +//! `DUAL_WRITE_GOLDEN=1 cargo test -p aien-scheduler --test dual_decision_golden`. +//! On the candidate commit the test compares; it never writes unless asked. + +mod dual_common; + +use dual_common::{build, canonical_json, run, scenarios, ScenarioTrace}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::PathBuf; + +fn fixture_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/dual_serve_admit_preempt.golden.json") +} + +fn all_traces() -> Vec { + scenarios() + .iter() + .map(|s| { + let (mut scheduler, kv) = build(s); + run(s, &mut scheduler, &kv) + }) + .collect() +} + +fn digests(traces: &[ScenarioTrace]) -> BTreeMap { + traces + .iter() + .map(|t| { + let hex = Sha256::digest(canonical_json(t)) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + (t.name.clone(), format!("sha256:{hex}")) + }) + .collect() +} + +#[test] +fn decisions_match_golden_fixture_from_base_commit() { + let now = digests(&all_traces()); + let path = fixture_path(); + + if std::env::var_os("DUAL_WRITE_GOLDEN").is_some() { + let bytes = serde_json::to_vec_pretty(&now).expect("serialize"); + std::fs::write(&path, &bytes).expect("write golden fixture"); + eprintln!("wrote {} ({} bytes)", path.display(), bytes.len()); + return; + } + + let golden = std::fs::read(&path).unwrap_or_else(|e| { + panic!( + "missing golden fixture {}: {e}. Produce it on the base commit with DUAL_WRITE_GOLDEN=1", + path.display() + ) + }); + let golden: BTreeMap = serde_json::from_slice(&golden).expect("parse golden"); + assert_eq!( + now.keys().collect::>(), + golden.keys().collect::>(), + "scenario set differs from the golden fixture" + ); + for (name, digest) in &now { + assert_eq!( + digest, &golden[name], + "scenario {name} decides differently from the base commit" + ); + } +} + +#[test] +fn workload_is_deterministic_run_to_run() { + let a = all_traces(); + let b = all_traces(); + assert!(canonical_json(&a) == canonical_json(&b)); +} + +#[test] +fn drained_scenarios_leak_nothing() { + for s in scenarios() { + let (mut scheduler, kv) = build(&s); + let trace = run(&s, &mut scheduler, &kv); + if s.expect_drained { + assert_eq!( + trace.final_kv.allocated_blocks, 0, + "{}: KV blocks held", + s.name + ); + assert_eq!(trace.final_kv.active_tables, 0, "{}: tables left", s.name); + assert!(trace.final_kv.active_blocks.is_empty(), "{}", s.name); + assert_eq!(trace.final_scheduler.running, 0, "{}", s.name); + assert_eq!(trace.final_scheduler.waiting, 0, "{}", s.name); + assert_eq!(trace.final_scheduler.preempted, 0, "{}", s.name); + assert_eq!(trace.final_scheduler.arena_active, 0, "{}", s.name); + } else { + // The refused request stays queued and never allocated. + assert_eq!(trace.final_kv.allocated_blocks, 0, "{}", s.name); + assert!( + trace.steps.iter().any(|st| st.error.is_some()), + "{}: expected a refusal", + s.name + ); + } + } +} diff --git a/crates/aien-scheduler/tests/dual_observer_overhead_bench.rs b/crates/aien-scheduler/tests/dual_observer_overhead_bench.rs new file mode 100644 index 00000000..566d3e41 --- /dev/null +++ b/crates/aien-scheduler/tests/dual_observer_overhead_bench.rs @@ -0,0 +1,279 @@ +//! Overhead of the `serve.admit_preempt` read-only tap (DUAL-3a). +//! +//! Manual benchmark, ignored by default (no timing assertion lives in CI): +//! +//! ```text +//! cargo test -p aien-scheduler --release --test dual_observer_overhead_bench -- --ignored --nocapture +//! ``` +//! +//! Three arms run the whole pre-registered workload set on fresh state: +//! +//! - `absent`: no observer installed (the production configuration); +//! - `counting`: `CountingObserver`, which serializes each record to count +//! bytes and keeps nothing (the cost of producing records); +//! - `recording`: `RecordingObserver`, which clones and keeps every record. +//! +//! Each arm runs `ROUNDS` rounds and reports the median wall time, decision +//! count, records emitted, serialized bytes emitted and heap allocations +//! (counted by a wrapping global allocator). The acceptance threshold is +//! pre-registered in the evidence receipt, not here. + +mod dual_common; + +use aien_scheduler::dual_observer::{CountingObserver, RecordingObserver}; +use dual_common::{build, run, scenarios}; +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::Arc; +use std::time::Instant; + +struct CountingAlloc; + +static ALLOCS: AtomicU64 = AtomicU64::new(0); +static ALLOC_BYTES: AtomicU64 = AtomicU64::new(0); + +unsafe impl GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + ALLOCS.fetch_add(1, Relaxed); + ALLOC_BYTES.fetch_add(layout.size() as u64, Relaxed); + System.alloc(layout) + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + System.dealloc(ptr, layout) + } +} + +#[global_allocator] +static GLOBAL: CountingAlloc = CountingAlloc; + +const ROUNDS: usize = 7; + +#[derive(Debug, Clone, Copy)] +struct Arm { + name: &'static str, + wall_ns_median: u128, + wall_ns_min: u128, + decisions: usize, + records: u64, + bytes: u64, + allocs: u64, + alloc_bytes: u64, +} + +fn median(v: &mut [u128]) -> u128 { + v.sort_unstable(); + v[v.len() / 2] +} + +fn arm(name: &'static str, mode: u8) -> Arm { + let set = scenarios(); + let mut walls = Vec::with_capacity(ROUNDS); + let mut decisions = 0; + let mut records = 0u64; + let mut bytes = 0u64; + let mut allocs = 0u64; + let mut alloc_bytes = 0u64; + for _ in 0..ROUNDS { + let mut round_decisions = 0; + let mut round_records = 0u64; + let mut round_bytes = 0u64; + let a0 = ALLOCS.load(Relaxed); + let b0 = ALLOC_BYTES.load(Relaxed); + let t0 = Instant::now(); + for s in &set { + let (mut scheduler, kv) = build(s); + let counting = Arc::new(CountingObserver::new()); + let recording = Arc::new(RecordingObserver::new()); + match mode { + 1 => scheduler.set_decision_observer(Some(counting.clone())), + 2 => scheduler.set_decision_observer(Some(recording.clone())), + _ => {} + } + let trace = run(s, &mut scheduler, &kv); + round_decisions += trace.decisions; + match mode { + 1 => { + round_records += counting.records(); + round_bytes += counting.bytes(); + } + 2 => { + let recs = recording.take(); + round_records += recs.len() as u64; + round_bytes += recs + .iter() + .map(|r| serde_json::to_vec(r).unwrap().len() as u64) + .sum::(); + } + _ => {} + } + } + let wall = t0.elapsed().as_nanos(); + let a1 = ALLOCS.load(Relaxed); + let b1 = ALLOC_BYTES.load(Relaxed); + walls.push(wall); + decisions = round_decisions; + records = round_records; + bytes = round_bytes; + allocs = a1 - a0; + alloc_bytes = b1 - b0; + } + Arm { + name, + wall_ns_median: median(&mut walls), + wall_ns_min: *walls.iter().min().unwrap(), + decisions, + records, + bytes, + allocs, + alloc_bytes, + } +} + +#[test] +#[ignore = "manual overhead benchmark; run with --ignored --nocapture in release"] +fn dual_observer_overhead() { + // Warm up once so the first arm does not pay for page faults alone. + let _ = arm("warmup", 0); + let absent = arm("absent", 0); + let counting = arm("counting", 1); + let recording = arm("recording", 2); + let absent2 = arm("absent_repeat", 0); + + println!("DUAL serve.admit_preempt observer overhead, {ROUNDS} rounds per arm, whole workload set per round"); + println!( + "{:<14} {:>14} {:>14} {:>10} {:>9} {:>12} {:>10} {:>12} {:>8}", + "arm", + "median_ms", + "min_ms", + "decisions", + "records", + "bytes", + "allocs", + "alloc_bytes", + "ratio" + ); + for a in [absent, counting, recording, absent2] { + println!( + "{:<14} {:>14.3} {:>14.3} {:>10} {:>9} {:>12} {:>10} {:>12} {:>8.3}", + a.name, + a.wall_ns_median as f64 / 1e6, + a.wall_ns_min as f64 / 1e6, + a.decisions, + a.records, + a.bytes, + a.allocs, + a.alloc_bytes, + a.wall_ns_median as f64 / absent.wall_ns_median as f64 + ); + } + // Deterministic facts (not timing): records equal decisions when a tap is on. + assert_eq!(counting.records, counting.decisions as u64); + assert_eq!(recording.records, recording.decisions as u64); + assert_eq!(absent.records, 0); + assert_eq!(absent.decisions, counting.decisions); +} + +/// Exploratory (NOT pre-registered) protocol added after the first run: arms +/// interleaved round by round so clock scaling and cache warmth hit every arm +/// alike, 50 rounds, medians. Reported in the receipt as post-hoc only; it +/// does not replace the pre-registered verdict above. +#[test] +#[ignore = "manual overhead benchmark (interleaved, exploratory); --ignored --nocapture in release"] +fn dual_observer_overhead_interleaved() { + const N: usize = 50; + let set = scenarios(); + let mut absent_w = Vec::with_capacity(N); + let mut counting_w = Vec::with_capacity(N); + let mut recording_w = Vec::with_capacity(N); + let mut absent_a = Vec::with_capacity(N); + let mut counting_a = Vec::with_capacity(N); + let mut recording_a = Vec::with_capacity(N); + let mut decisions = 0usize; + let mut records = 0u64; + let mut bytes = 0u64; + + let run_arm = |mode: u8, walls: &mut Vec, allocs: &mut Vec| { + let a0 = ALLOCS.load(Relaxed); + let t0 = Instant::now(); + let mut d = 0usize; + let mut r = 0u64; + let mut b = 0u64; + for s in &set { + let (mut scheduler, kv) = build(s); + let counting = Arc::new(CountingObserver::new()); + let recording = Arc::new(RecordingObserver::new()); + match mode { + 1 => scheduler.set_decision_observer(Some(counting.clone())), + 2 => scheduler.set_decision_observer(Some(recording.clone())), + _ => {} + } + let trace = run(s, &mut scheduler, &kv); + d += trace.decisions; + match mode { + 1 => { + r += counting.records(); + b += counting.bytes(); + } + 2 => { + let recs = recording.take(); + r += recs.len() as u64; + b += recs + .iter() + .map(|x| serde_json::to_vec(x).unwrap().len() as u64) + .sum::(); + } + _ => {} + } + } + walls.push(t0.elapsed().as_nanos()); + allocs.push(ALLOCS.load(Relaxed) - a0); + (d, r, b) + }; + + // Warm-up round for every arm, discarded. + let (mut w, mut a) = (Vec::new(), Vec::new()); + for mode in 0..3u8 { + run_arm(mode, &mut w, &mut a); + } + for _ in 0..N { + let (d, _, _) = run_arm(0, &mut absent_w, &mut absent_a); + decisions = d; + let (_, r, b) = run_arm(1, &mut counting_w, &mut counting_a); + records = r; + bytes = b; + run_arm(2, &mut recording_w, &mut recording_a); + } + let med = |v: &mut Vec| median(v); + let (ma, mc, mr) = ( + med(&mut absent_w), + med(&mut counting_w), + med(&mut recording_w), + ); + println!("DUAL serve.admit_preempt observer overhead, INTERLEAVED exploratory protocol, {N} rounds, median of per-round wall"); + println!( + "{:<10} {:>12} {:>12} {:>10} {:>9} {:>12} {:>10} {:>8}", + "arm", "median_ms", "min_ms", "decisions", "records", "bytes", "allocs", "ratio" + ); + for (name, w, al, rec, by) in [ + ("absent", &absent_w, &absent_a, 0u64, 0u64), + ("counting", &counting_w, &counting_a, records, bytes), + ("recording", &recording_w, &recording_a, records, bytes), + ] { + let m = { + let mut c = w.clone(); + median(&mut c) + }; + println!( + "{:<10} {:>12.3} {:>12.3} {:>10} {:>9} {:>12} {:>10} {:>8.3}", + name, + m as f64 / 1e6, + *w.iter().min().unwrap() as f64 / 1e6, + decisions, + rec, + by, + al[al.len() / 2], + m as f64 / ma as f64 + ); + } + let _ = (mc, mr); +} diff --git a/crates/aien-scheduler/tests/dual_observer_parity.rs b/crates/aien-scheduler/tests/dual_observer_parity.rs new file mode 100644 index 00000000..4af95889 --- /dev/null +++ b/crates/aien-scheduler/tests/dual_observer_parity.rs @@ -0,0 +1,379 @@ +//! Decision parity for the `serve.admit_preempt` read-only tap (DUAL-3a). +//! +//! For every pre-registered scenario the same deterministic workload runs +//! twice on fresh state: once with no observer, once with a +//! `RecordingObserver`. The canonical trace of every decision (batches, +//! errors, outputs, KV accounting, scheduler counters) must be byte-for-byte +//! identical, one record must exist per decision, and each record must agree +//! with the batch it describes. +//! +//! Negative control: with the Cargo feature +//! `dual_observer_mutant_changes_decision` the scheduler stops admitting after +//! one grant whenever an observer is installed. `observer_presence_changes_no_decision` +//! must FAIL under that feature (see the evidence receipt); the feature is +//! never on in a real build. + +mod dual_common; + +use aien_scheduler::dual_observer::{ + AdmissionVerdict, AdmitPreemptRecord, BatchOutcome, DecisionObserver, RecordingObserver, + SERVE_ADMIT_PREEMPT_SITE, +}; +use aien_scheduler::{AienScheduler, SequenceId}; +use dual_common::{build, canonical_json, run, scenario, scenarios, Scenario, ScenarioTrace}; +use std::sync::Arc; + +fn run_without_observer(s: &Scenario) -> ScenarioTrace { + let (mut scheduler, kv) = build(s); + assert!(!scheduler.decision_observer_installed()); + run(s, &mut scheduler, &kv) +} + +fn run_with_observer(s: &Scenario) -> (ScenarioTrace, Vec) { + let (mut scheduler, kv) = build(s); + let observer = Arc::new(RecordingObserver::new()); + scheduler.set_decision_observer(Some(observer.clone())); + assert!(scheduler.decision_observer_installed()); + let trace = run(s, &mut scheduler, &kv); + (trace, observer.take()) +} + +#[test] +fn observer_presence_changes_no_decision() { + for s in scenarios() { + let absent = run_without_observer(&s); + let (present, records) = run_with_observer(&s); + assert!( + canonical_json(&absent) == canonical_json(&present), + "scenario {}: decisions differ with the observer installed", + s.name + ); + assert_eq!( + records.len(), + present.decisions, + "scenario {}: one record per decision", + s.name + ); + } +} + +#[test] +fn kv_accounting_identical_with_and_without_observer() { + for s in scenarios() { + let absent = run_without_observer(&s); + let (present, _) = run_with_observer(&s); + for (a, p) in absent.steps.iter().zip(present.steps.iter()) { + assert_eq!(a.kv, p.kv, "scenario {} step {}", s.name, a.index); + } + assert_eq!(absent.final_kv, present.final_kv, "{}", s.name); + } +} + +/// Each record must describe the batch the scheduler actually produced. +#[test] +fn records_agree_with_the_batches_they_describe() { + for s in scenarios() { + let (trace, records) = run_with_observer(&s); + for (step, record) in trace.steps.iter().zip(records.iter()) { + assert_eq!(record.site, SERVE_ADMIT_PREEMPT_SITE); + match (&step.batch, &step.error, &record.choice.outcome) { + ( + Some(batch), + None, + BatchOutcome::Batch { + prefill_requests, + decode_requests, + batch_tokens, + }, + ) => { + assert_eq!(record.step_id, batch.step_id, "{}", s.name); + assert_eq!(*prefill_requests, batch.prefill.len()); + assert_eq!(*decode_requests, batch.decode.len()); + let tokens: usize = + batch.prefill.iter().map(|(_, t, _)| t.len()).sum::() + + batch.decode.len(); + assert_eq!(*batch_tokens, tokens); + let decode_ids: Vec = record + .choice + .decode_scheduled + .iter() + .map(|id| id.to_u64()) + .collect(); + assert_eq!(decode_ids, batch.decode, "{} step {}", s.name, step.index); + let prefill_ids: Vec<(u64, usize)> = record + .choice + .prefill_scheduled + .iter() + .map(|(id, n)| (id.to_u64(), *n)) + .collect(); + let batch_prefill: Vec<(u64, usize)> = batch + .prefill + .iter() + .map(|(id, t, _)| (*id, t.len())) + .collect(); + assert_eq!(prefill_ids, batch_prefill, "{} step {}", s.name, step.index); + } + (None, None, BatchOutcome::Empty) => { + assert!(record.choice.decode_scheduled.is_empty()); + assert!(record.choice.prefill_scheduled.is_empty()); + } + (None, Some(err), BatchOutcome::Error(recorded)) => { + assert_eq!(err, recorded); + assert!(record + .alternatives + .admission_examined + .iter() + .any(|c| c.verdict == AdmissionVerdict::RefusedPoolExhausted)); + } + other => panic!( + "{} step {}: inconsistent outcome {:?}", + s.name, step.index, other + ), + } + // Exit readings equal what the trace read right after the step's + // backend run only for counts the backend run does not change; + // the scheduler counts at exit are asserted against the record. + assert_eq!(record.kv_at_exit.total_blocks, step.kv.total_blocks); + assert_eq!(record.limits.max_batch_size, s.config.max_batch_size); + assert_eq!(record.limits.watermark_blocks, s.config.watermark_blocks); + assert_eq!( + record.kv_at_entry.allocated_blocks + record.kv_at_entry.free_blocks, + record.kv_at_entry.total_blocks + ); + assert_eq!( + record.kv_at_exit.allocated_blocks + record.kv_at_exit.free_blocks, + record.kv_at_exit.total_blocks + ); + } + } +} + +#[test] +fn preemption_records_name_the_ranked_victims_and_the_choice() { + let s = scenario("preemption_watermark"); + let (_, records) = run_with_observer(&s); + let preempting: Vec<&AdmitPreemptRecord> = records + .iter() + .filter(|r| !r.choice.preempted.is_empty()) + .collect(); + assert!( + !preempting.is_empty(), + "the scenario must preempt at least once" + ); + for r in &preempting { + assert!(r.below_watermark_at_entry); + assert!(!r.alternatives.preemption_victims_considered.is_empty()); + // The victim is the first ranked candidate (lowest priority). + assert_eq!( + r.choice.preempted[0], + r.alternatives.preemption_victims_considered[0].seq + ); + let min_priority = r + .alternatives + .preemption_victims_considered + .iter() + .map(|v| v.priority) + .min() + .unwrap(); + assert_eq!( + r.alternatives.preemption_victims_considered[0].priority, + min_priority + ); + // No admission happens in a step that preempted. + assert!(r.alternatives.admission_examined.is_empty()); + } + // slot 2 has priority 1 (Normal), slot 1 priority 3 (Realtime): slot 2 is the victim. + assert_eq!( + preempting[0].choice.preempted[0], + SequenceId::new(2, 1).unwrap() + ); +} + +#[test] +fn tie_victim_is_first_in_running_order() { + let s = scenario("preemption_tie_equal_priority"); + let (_, records) = run_with_observer(&s); + let r = records + .iter() + .find(|r| !r.choice.preempted.is_empty()) + .expect("a preemption"); + let victims = &r.alternatives.preemption_victims_considered; + assert_eq!(victims.len(), 2); + assert_eq!(victims[0].priority, victims[1].priority); + assert_eq!(victims[0].seq, r.alternatives.running_at_entry[0]); + assert_eq!(r.choice.preempted[0], r.alternatives.running_at_entry[0]); +} + +#[test] +fn no_preemption_records_rank_no_victims() { + let s = scenario("no_preemption_sufficient_pool"); + let (_, records) = run_with_observer(&s); + for r in &records { + assert!(!r.below_watermark_at_entry); + assert!(r.alternatives.preemption_victims_considered.is_empty()); + assert!(r.choice.preempted.is_empty()); + } +} + +#[test] +fn capacity_boundary_records_carry_the_compared_numbers() { + let below = run_with_observer(&scenario("capacity_one_below")).1; + let at = run_with_observer(&scenario("capacity_exactly_at")).1; + let above = run_with_observer(&scenario("capacity_one_above_refused")).1; + + let first_admit = + |records: &[AdmitPreemptRecord]| records[0].alternatives.admission_examined[0].clone(); + let b = first_admit(&below); + assert_eq!(b.needed_blocks, 7); + assert_eq!(b.pool_blocks, 8); + assert!(matches!( + b.verdict, + AdmissionVerdict::AdmittedPrefill { new_blocks: 7, .. } + )); + + let a = first_admit(&at); + assert_eq!(a.needed_blocks, 8); + assert_eq!(a.min_needed, 8); + assert_eq!(a.free_blocks, 8); + assert!(matches!( + a.verdict, + AdmissionVerdict::AdmittedPrefill { new_blocks: 8, .. } + )); + + let o = first_admit(&above); + assert_eq!(o.needed_blocks, 9); + assert_eq!(o.min_needed, 9); + assert_eq!(o.pool_blocks, 8); + assert_eq!(o.verdict, AdmissionVerdict::RefusedPoolExhausted); + assert!(matches!(above[0].choice.outcome, BatchOutcome::Error(_))); +} + +#[test] +fn wait_for_blocks_is_recorded_while_something_runs() { + let (_, records) = run_with_observer(&scenario("capacity_wait_while_running")); + assert!(records.iter().any(|r| r + .alternatives + .admission_examined + .iter() + .any(|c| c.verdict == AdmissionVerdict::WaitForBlocks))); + assert!(records + .iter() + .all(|r| !matches!(r.choice.outcome, BatchOutcome::Error(_)))); +} + +#[test] +fn fanout_children_enter_decode_on_existing_tables() { + for name in ["fanout_32_way", "fanout_500_way"] { + let s = scenario(name); + let expected = if name == "fanout_32_way" { 32 } else { 500 }; + let (trace, records) = run_with_observer(&s); + let decode_admits: usize = records + .iter() + .flat_map(|r| r.alternatives.admission_examined.iter()) + .filter(|c| c.verdict == AdmissionVerdict::AdmittedDecode) + .count(); + assert_eq!( + decode_admits, expected, + "{name}: every child admitted via its shared table" + ); + assert_eq!(trace.final_kv.allocated_blocks, 0, "{name}: no leak"); + assert_eq!( + trace.final_scheduler.finished_requests as usize, + expected + 1 + ); + // A step admitting children records a reserved-block ledger that grows + // by each child's incremental need. + let admit_step = records + .iter() + .find(|r| { + r.alternatives + .admission_examined + .iter() + .any(|c| c.verdict == AdmissionVerdict::AdmittedDecode) + }) + .unwrap(); + let admitted: Vec<_> = admit_step + .alternatives + .admission_examined + .iter() + .filter(|c| c.verdict == AdmissionVerdict::AdmittedDecode) + .collect(); + for w in admitted.windows(2) { + assert_eq!( + w[1].reserved_blocks, + w[0].reserved_blocks + w[0].needed_blocks + ); + } + } +} + +#[test] +fn queue_exhaustion_records_show_the_batch_limit_stopping_admission() { + let s = scenario("queue_exhaustion_batch_limit"); + let (trace, records) = run_with_observer(&s); + assert_eq!(records[0].alternatives.waiting_at_entry.len(), 12); + let admitted_first_step = records[0] + .alternatives + .admission_examined + .iter() + .filter(|c| matches!(c.verdict, AdmissionVerdict::AdmittedPrefill { .. })) + .count(); + assert_eq!(admitted_first_step, 4); + assert_eq!(records[0].waiting_count_at_exit, 8); + assert_eq!(trace.final_scheduler.waiting, 0); +} + +#[test] +fn empty_step_record_is_empty() { + let (_, records) = run_with_observer(&scenario("no_admission_empty_queues")); + assert_eq!(records.len(), 3); + for (i, r) in records.iter().enumerate() { + assert_eq!(r.step_id, i as u64 + 1); + assert_eq!(r.choice.outcome, BatchOutcome::Empty); + assert!(r.alternatives.running_at_entry.is_empty()); + assert_eq!(r.arena_active_at_entry, 0); + assert_eq!(r.kv_at_entry, r.kv_at_exit); + } +} + +/// Removing the observer mid-run stops the records and changes nothing else. +#[test] +fn observer_can_be_removed_and_decisions_still_match() { + let s = scenario("admission_basic"); + let absent = run_without_observer(&s); + let (mut scheduler, kv) = build(&s); + let observer = Arc::new(RecordingObserver::new()); + scheduler.set_decision_observer(Some(observer.clone())); + scheduler.set_decision_observer(None); + let present_then_removed = run(&s, &mut scheduler, &kv); + assert!(canonical_json(&absent) == canonical_json(&present_then_removed)); + assert!(observer.is_empty()); +} + +/// A second, independent observer implementation receives identical records +/// to the recording one: the record is a function of the decision alone. +struct DigestObserver(std::sync::Mutex>>); + +impl DecisionObserver for DigestObserver { + fn observe_admit_preempt(&self, record: &AdmitPreemptRecord) { + self.0.lock().unwrap().push(canonical_json(record)); + } +} + +#[test] +fn two_observers_see_the_same_records() { + let s = scenario("preemption_watermark"); + let (_, recorded) = run_with_observer(&s); + let (mut scheduler, kv) = build(&s); + let digest = Arc::new(DigestObserver(Default::default())); + scheduler.set_decision_observer(Some(digest.clone())); + let _ = run(&s, &mut scheduler, &kv); + let seen = digest.0.lock().unwrap().clone(); + let expected: Vec> = recorded.iter().map(canonical_json).collect(); + assert_eq!(seen, expected); +} + +#[allow(dead_code)] +fn _scheduler_type_check(s: &AienScheduler) -> bool { + s.decision_observer_installed() +} diff --git a/crates/aien-scheduler/tests/fixtures/dual_serve_admit_preempt.golden.json b/crates/aien-scheduler/tests/fixtures/dual_serve_admit_preempt.golden.json new file mode 100644 index 00000000..1a84f729 --- /dev/null +++ b/crates/aien-scheduler/tests/fixtures/dual_serve_admit_preempt.golden.json @@ -0,0 +1,15 @@ +{ + "admission_basic": "sha256:9c300928d2cb099a0bc5a58f7c58ee5c18cbd7388e296fa4d09ffadf1cbe4d0f", + "capacity_exactly_at": "sha256:b702d8e7d74372f4323cd72844e97ddb13b1272df7db5b219105af6567d9b7d4", + "capacity_one_above_refused": "sha256:610ae66a41ff4bf49ae662e672a3577ebca295854abd03106ff96e5e08d5c55b", + "capacity_one_below": "sha256:7dc77eff7a44880036e8e3db34d99409c57b9e34fdaed4e9832c222f93448d61", + "capacity_wait_while_running": "sha256:b2ff73f5d82efca2cd89d4ef91d4bd17ce6ae02f9f22699697b11713d72a626f", + "chunked_prefill_continuation": "sha256:7ec0601caf47af66f06a2269add4641806eec29247e0e11b7c803b3df5505e3c", + "fanout_32_way": "sha256:275d6551a8de19e7df247346c08e5731c2fa9c2a9c0933089be2d3c6ea078ba4", + "fanout_500_way": "sha256:6074ae12ee682c7d60a57329555f4bfa0fe9a320187859fa861370c494955eef", + "no_admission_empty_queues": "sha256:51a820ed485940ed7783f1ad347bd002d115ba79e309e24a48c25b4ad1e82b5d", + "no_preemption_sufficient_pool": "sha256:e59b1e627bdeee841bc09d1bac04c6bd8a02cd546c12d961a5a5535727af5212", + "preemption_tie_equal_priority": "sha256:34eb100648c6786e19ffd65c6a35c69594f5c10b4ffea9ce0ef3807c6986bef7", + "preemption_watermark": "sha256:12f73f73f618f855d4d53ed93884bd5b871456c824939702157413a2bde729fb", + "queue_exhaustion_batch_limit": "sha256:c643b030d610377c0bd1f514e71952cf2528a6380a2fb478eab77bd37db41169" +} \ No newline at end of file diff --git a/docs/campaigns/dual/2026-10-04-serve-observer-receipt.md b/docs/campaigns/dual/2026-10-04-serve-observer-receipt.md new file mode 100644 index 00000000..f22fa9b5 --- /dev/null +++ b/docs/campaigns/dual/2026-10-04-serve-observer-receipt.md @@ -0,0 +1,251 @@ +# Receipt: DUAL `serve.admit_preempt` read-only observer (DUAL-3a instrumentation) + +Program: ARCH-0031 "DUAL, Constraint Pricing for Soft Resource Budgets", §7.3 +(decision sites observed through a read-only tap), gate DUAL-3 prerequisite +"at least one registered decision site with a read-only tap". +Site: `serve.admit_preempt` (DUAL_CURRENT_STATE §4), production owner +`aien-scheduler::AienScheduler::build_scheduled_batch`. + +**Gate verdict: none claimed.** This receipt records instrumentation +(DUAL-3a). `DUAL_ADVISORY_SCHEDULER` is NOT claimed PASS: no +`DualRecommendation` is produced, no pre-registered workload set with +recommendation-versus-actual analysis exists yet, and no prediction-quality +claim is made. The tap changes no production decision; the evidence below is +that it changes none. + +## 1. Identity + +| Field | Value | +|---|---| +| Repository | `aien-dev/aien-sovereign-core` | +| Base commit (GitHub `main`) | `91fba8fc0f00fd09fc3e9a6137522af3ae79c4e1` | +| Branch | `dual/serve-observer` | +| Candidate commit | filled in §9 after the final commit | +| Tree | clean at each recorded command (`git status --short` empty) | +| Compiler | `rustc 1.98.1 (48a229cea 2026-09-01)`, `cargo 1.98.1 (797e8a9bc 2026-08-05)` | +| Build config | `dev` profile for tests (as CI), `release` profile for the benchmark only | +| Host | NVIDIA DGX Spark, GB10, aarch64, Linux 7.0.0-1019-nvidia, 20 CPUs | +| GPU exercised | **No.** Every test and the benchmark run `MockInferenceBackend` on the host CPU. No GB10 kernel, no NVRM call, no model. | +| Workspace path | fresh clone `~/workspace/dual/sc-observer` | + +## 2. What changed (code) + +- `crates/aien-scheduler/src/dual_observer.rs` (new): `DecisionObserver` trait + (`fn observe_admit_preempt(&self, &AdmitPreemptRecord)`, returns `()`), the + immutable `AdmitPreemptRecord` (site id, step counter, limits, KV readings at + entry and exit, arena active count, ranked preemption victims, every running + sequence examined with its verdict, every queue head examined with the exact + numbers compared, the chosen preempted / decode / prefill-chunk sets, the + batch outcome), `RecordingObserver`, `CountingObserver`. +- `crates/aien-scheduler/src/lib.rs`: `AienScheduler.observer: + Option>` (default `None`), + `set_decision_observer`, `decision_observer_installed`; + `build_scheduled_batch` is now a thin wrapper around + `build_scheduled_batch_traced(&mut Option)`, which is + the former body with `if let Some(t) = trace` inserts. No arithmetic, + ordering, lock, allocation or KV call of the decision moved or changed. +- `crates/aien-scheduler/Cargo.toml`: dev-dependencies `async-trait`, `sha2` + (both already in `Cargo.lock`); mutant feature + `dual_observer_mutant_changes_decision` (off; negative control, §5). +- Tests: `tests/dual_common/mod.rs` (deterministic workload set + canonical + trace), `tests/dual_decision_golden.rs`, `tests/dual_observer_parity.rs`, + `tests/dual_observer_overhead_bench.rs` (ignored, manual), + `tests/fixtures/dual_serve_admit_preempt.golden.json`. + +Untouched: `aien-kv-cache` (refcounts, copy-on-write, allocation failure +paths, watermark enforcement), `aien-runtime`, `aien-abi-core`. No pressure +or metric authorizes anything; the hook has no return value. + +## 3. Pre-registered workload set + +Thirteen scripted scenarios in `tests/dual_common/mod.rs::scenarios()`, run +on `MockInferenceBackend` (fixed tokens, no sleep), timing fields excluded +from every trace: + +| Scenario | Exercises | +|---|---| +| `admission_basic` | admission of four requests, run to length limit, drain | +| `no_admission_empty_queues` | `Ok(None)` steps, nothing touched | +| `chunked_prefill_continuation` | 300-token prompt, 64-token chunks, 100-token budget, beside a decoding sequence | +| `preemption_watermark` | 6-block pool, watermark 3: lower priority preempted, readmitted | +| `preemption_tie_equal_priority` | equal priorities: stable sort, first in running order is the victim | +| `no_preemption_sufficient_pool` | same requests, 256-block pool, no victim ranked | +| `queue_exhaustion_batch_limit` | 12 requests, batch of 4, admission stops on the batch limit each step | +| `capacity_one_below` | 7 of 8 blocks needed: admitted | +| `capacity_exactly_at` | 8 of 8: admitted | +| `capacity_one_above_refused` | 9 of 8, nothing running: `KV_POOL_EXHAUSTED` error, request stays queued, nothing allocated | +| `capacity_wait_while_running` | shortfall while something runs: waits without error | +| `fanout_32_way` | 32 children share a prefilled parent's blocks, admitted straight into decode | +| `fanout_500_way` | same with 500 children | + +Counter wrap: `step_id` is a `u64` incremented with `+=` (unchanged, would +panic in debug at 2^64 steps); the record copies it, nothing else. Not +exercised: no test crosses the wrap because the production code does not +either. The record's `step_id` equals the batch's `step_id` in every test. + +## 4. Tests and results + +Commands run from the repository root on the candidate tree. Results are +filled in §9 from the actual runs. + +| # | Command | Purpose | +|---|---|---| +| T1 | `DUAL_WRITE_GOLDEN=1 cargo test -p aien-scheduler --test dual_decision_golden decisions_match_golden` on a worktree at the base commit, with `tests/dual_common`, `tests/dual_decision_golden.rs` and the two dev-dependencies copied in | before/after: produce per-scenario sha256 of every decision on the base commit | +| T2 | `cargo test -p aien-scheduler --test dual_decision_golden` | candidate decides identically to the base commit; workload deterministic run to run; drained scenarios hold zero KV blocks, zero tables, zero arena records, empty queues | +| T3 | `cargo test -p aien-scheduler --test dual_observer_parity` | observer absent vs `RecordingObserver`: canonical trace bytes identical, KV accounting identical per step, one record per decision, records agree with the batches, preemption / tie / capacity / fan-out / queue-exhaustion / empty-step records carry the right facts | +| T4 | `cargo test -p aien-scheduler --doc` | two `compile_fail` doctests: an observer cannot mutate the record or return a choice | +| T5 | `cargo test -p aien-scheduler -p aien-kv-cache -p aien-runtime -- --test-threads=1` | existing scheduler, KV mutation / copy-on-write / incremental-blocks, runtime World lifecycle, spine, swarm, 500-branch tests | +| T6 | `cargo clippy -p aien-scheduler --all-targets -- -D warnings`; `cargo fmt --all -- --check` | CI invariants | +| T7 | `crumb verify .` | Crumb protocol | + +Sanitizers / miri: not used; the repository does not run them. + +## 5. Negative control + +Two layers. + +**By type.** `DecisionObserver::observe_admit_preempt(&self, record: +&AdmitPreemptRecord)` returns `()`. The observer holds no reference to the +scheduler, KV manager or arena. Two `compile_fail` doctests in +`dual_observer.rs` show that (a) mutating the record and (b) returning a +different `AdmitPreemptChoice` do not compile (T4). + +**By injected mutant.** Cargo feature `dual_observer_mutant_changes_decision` +makes the admission loop stop after one grant whenever an observer is +installed (a decision change that only the tap's presence triggers). With it +on, the parity test must fail: + +``` +cargo test -p aien-scheduler --features dual_observer_mutant_changes_decision --test dual_observer_parity observer_presence_changes_no_decision +test observer_presence_changes_no_decision ... FAILED +thread 'observer_presence_changes_no_decision' panicked at crates/aien-scheduler/tests/dual_observer_parity.rs:46:9: +scenario admission_basic: decisions differ with the observer installed +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 12 filtered out +exit=101 +``` + +Full parity file under the mutant: 4 failed (`observer_presence_changes_no_decision`, +`kv_accounting_identical_with_and_without_observer`, +`queue_exhaustion_records_show_the_batch_limit_stopping_admission`, +`fanout_children_enter_decode_on_existing_tables`), 9 passed. The feature is +off by default and never enabled in CI; the mutant code stays in the tree, +disabled, so the control can be rerun (same convention as +`prefill_mutant_no_check`). + +## 6. Benchmark: pre-registered threshold (written and committed BEFORE the run) + +Command (release profile, host CPU, mock backend, whole workload set per +round, 7 rounds per arm, median reported): + +``` +cargo test -p aien-scheduler --release --test dual_observer_overhead_bench -- --ignored --nocapture +``` + +Arms: `absent` (no observer; production configuration), `counting` +(`CountingObserver`: serializes each record to count bytes, keeps nothing), +`recording` (`RecordingObserver`: clones and keeps every record), +`absent_repeat` (noise reference). + +Pre-registered acceptance (frozen here, commit before the run): + +| Id | Measure | Threshold | Why | +|---|---|---|---| +| B1 | `median(counting) / median(absent)` | **≤ 1.25** | The tap must be cheap enough to stay installed through the DUAL-3 observation period. On the mock backend the step has no model compute, so this ratio is a strict upper bound on the production fraction (real steps are dominated by the forward pass). No prior threshold exists in the repository for this tap; 25 % is the author's choice and it is not moved after the run. | +| B2 | `records` emitted (counting and recording arms) | **== decisions** exactly | one record per decision, no drops, no duplicates | +| B3 | `absent` arm decision count | **== counting arm decision count** | the tap adds or removes no scheduling step | +| B4 | `median(absent_repeat) / median(absent)` | reported, informational | machine noise reference for reading B1 | +| B5 | bytes emitted, heap allocations and bytes (global allocator counter) per arm | reported, no threshold | observer cost in memory terms for the DUAL-3 design | + +Not measured here: absent-arm wall time on the candidate against the base +commit. UNVERIFIED by timing; the before/after identity is proven by T1/T2 +(decisions) and by reading the diff (the absent path adds one +`Option::is_some()` and passes `None` through). + +If B1 fails the receipt says FAIL and the threshold stays. + +## 7. Results + +Filled in §9. + +## 8. Limits + +- Mock backend only. No real model, no GPU, no NVRM. +- The tap records the admission / preemption / chunk decision. It does not + record the `step()` post-processing (token append, finish, KV free on + finish), which is not a DUAL decision site. +- `RunningVerdict::GateRefusedReprefill`, `DecodeNoTable`, `NoRecord` and + `AdmissionVerdict::MissingRecord` are reachable only through internal state + manipulation; the pre-registered workloads do not reach them. UNVERIFIED + by test in this receipt (the code paths are plain copies of the + scheduler's own branches). +- Timing of the absent path versus the base commit: UNVERIFIED by + measurement (see §6). + +## 9. Run log (appended after the runs, nothing above this line edited) + +### 9.1 Test results (candidate tree, first commit `a2640c7` plus this appendix and the exploratory benchmark below) + +| # | Result | +|---|---| +| T1 | Base worktree at `91fba8fc0f00fd09fc3e9a6137522af3ae79c4e1` (`git worktree add /tmp/sc-base origin/main`, `tests/dual_common`, `tests/dual_decision_golden.rs` and the two dev-dependencies copied in, nothing else): `test decisions_match_golden_fixture_from_base_commit ... ok` with `DUAL_WRITE_GOLDEN=1`; wrote 13 per-scenario digests (1346 bytes). Regenerated once more after the final edit of `dual_common`; byte-identical. | +| T2 | `cargo test -p aien-scheduler --test dual_decision_golden`: 3 passed, 0 failed (golden digests match on the candidate; deterministic run to run; drained scenarios hold 0 KV blocks, 0 tables, 0 arena records, empty queues; the refusal scenario allocates nothing). | +| T3 | `cargo test -p aien-scheduler --test dual_observer_parity`: 13 passed, 0 failed. | +| T4 | `cargo test -p aien-scheduler --doc`: 2 passed (both `compile_fail`). | +| T5 | `cargo test -p aien-scheduler -p aien-kv-cache -p aien-runtime -- --test-threads=1`: 29 suites, 91 passed, 0 failed, 4 ignored (the ignored ones are the pre-existing real-checkpoint runtime tests and this benchmark). Exit 0. | +| T6 | `cargo fmt --all -- --check`: exit 0. `cargo clippy -p aien-scheduler --all-targets -- -D warnings`: exit 0. | +| T7 | `crumb compile .` then `crumb verify .` immediately before the commit: `OK: 13 crumbs current`. After the commit `crumb verify .` reports the root crumb STALE because `generated_at_commit` names the previous HEAD; pristine `main` at `91fba8f` reports the same (`crumb verify` in `/tmp/sc-base`: `FAIL: 1 of 13 crumbs stale`). This repository's CI runs no `crumb verify` step (grep of `.github/workflows/*.yml`). Recorded, not worked around. | + +Negative control: as §5 (mutant feature on: 4 of 13 parity tests FAIL, exit 101; feature off: 13 pass). + +### 9.2 Benchmark results, pre-registered protocol (§6) + +Command as pre-registered, release profile, run once after the threshold was committed: + +``` +DUAL serve.admit_preempt observer overhead, 7 rounds per arm, whole workload set per round +arm median_ms min_ms decisions records bytes allocs alloc_bytes ratio +absent 1.520 1.516 53 0 0 16537 2511522 1.000 +counting 2.033 1.952 53 53 329492 17059 3757374 1.337 +recording 1.182 1.177 53 53 329492 17253 3904970 0.778 +absent_repeat 0.903 0.899 53 0 0 16537 2511522 0.594 +``` + +| Id | Measured | Threshold | Verdict | +|---|---|---|---| +| B1 | `counting / absent` = **1.337** | ≤ 1.25 | **FAIL** (pre-registered; the threshold is not moved) | +| B2 | records = 53 = decisions, both tapped arms | == | PASS | +| B3 | decisions absent = 53 = counting | == | PASS | +| B4 | `absent_repeat / absent` = **0.594** | informational | the noise between two identical arms (41 %) is larger than the effect B1 tries to resolve; the pre-registered protocol (arms run back to back, 7 rounds, ~1.5 ms per round) cannot measure a 25 % bound on this host | +| B5 | bytes emitted 329,492 for 53 records (6.2 KB per record on average, dominated by the 500-way fan-out scenario's id lists); heap allocations absent 16,537, counting 17,059 (+522, about 10 per record), recording 17,253 (+716); alloc bytes 2.51 MB, 3.76 MB, 3.90 MB | reported | reported | + +**B1 is recorded as FAIL.** The protocol was under-powered (B4), which is a +defect of the pre-registration, not a reason to change the verdict. + +### 9.3 Exploratory measurement, NOT pre-registered (added after 9.2) + +Added after the run above: `dual_observer_overhead_interleaved` (same file), +arms interleaved absent / counting / recording in every round, 50 rounds, +one warm-up round per arm discarded, medians: + +``` +arm median_ms min_ms decisions records bytes allocs ratio +absent 0.909 0.901 53 0 0 16537 1.000 +counting 1.128 1.122 53 53 329492 17059 1.241 +recording 1.135 1.127 53 53 329492 17253 1.249 +``` + +Reading: about 4 µs of tap cost per decision on the mock backend +((1.128 − 0.909) ms / 53), where a mock step itself costs about 17 µs. This +is post-hoc and does not turn B1 into a pass. A future pre-registration +should use the interleaved protocol and state the absolute per-decision cost +beside the ratio, because the ratio on a compute-free mock backend overstates +the production fraction (a real step is milliseconds of forward pass). + +### 9.4 Verdict + +- Instrumentation delivered: read-only tap at `serve.admit_preempt`, decision + parity proven byte-for-byte against the base commit and between tap on/off, + negative control killed by type and by mutant. +- Benchmark B1: FAIL against the pre-registered 1.25 ratio; B2, B3 PASS; + exploratory interleaved 1.24 to 1.25 reported, not claimed. +- `DUAL_ADVISORY_SCHEDULER`: **not claimed** (see the top of this receipt). ```