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
GitHub aien-dev/aien-sovereign-core-mv#145 (code only)
Apply it
git checkout -b patch-112de427b72f719a cfd99827ca5483c08d549ca32c7ee3d3bde6f2d8 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/112de427b72f719a.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
145
d6455dad11bd43559daf60ce4d84fdb1269dcb2d
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":145,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/145","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:05Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aien-kv-cache/Cargo.toml b/crates/aien-kv-cache/Cargo.toml index 095b8d6d..bb4448d1 100644 --- a/crates/aien-kv-cache/Cargo.toml +++ b/crates/aien-kv-cache/Cargo.toml @@ -14,3 +14,9 @@ libc = "0.2" [target.'cfg(target_os = "linux")'.dependencies] aien-platform-linux = { path = "../aien-platform-linux" } + +[features] +# MUTANT ONLY (PREFILL-GATE). Never enable in a real build. Marks a freshly +# allocated block table PrefillReady (no completion fence). The prefill-gate +# tests must FAIL with this feature on; see scripts/prefill-gate/mutant.sh. +prefill_mutant_ready_at_alloc = [] diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs index 8d0236f9..66f920ee 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs @@ -605,11 +605,85 @@ pub struct KvBlock { pub is_shared: bool, } +/// Readiness of the K/V content behind a block table. +/// +/// Allocated is not computed: `allocate_sequence` only reserves and zeroes +/// blocks. Only the prefill completion fence (the point where the model +/// forward over the prompt span returned Ok, see `complete_prefill`) may move +/// a table to `PrefillReady`. Decode and sharing require `PrefillReady` or +/// `SharedFrozen`. Reclaimed is the absence of the table (`free_sequence`). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum PrefillState { + /// Blocks reserved and zeroed; no K/V computed. + #[default] + Allocated, + /// A model prefill over the prompt span has been issued but has not completed. + PrefillPending, + /// The completion fence fired: K/V for the prompt span is computed. + PrefillReady, + /// Ready and shared with at least one fork; the prefix is immutable. + SharedFrozen, +} + +impl PrefillState { + /// True only when the prompt K/V has been computed by a completed prefill. + pub fn is_ready(self) -> bool { + matches!( + self, + PrefillState::PrefillReady | PrefillState::SharedFrozen + ) + } +} + +/// Typed refusal from the prefill readiness gate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PrefillGateError { + /// No block table exists for this sequence. + UnknownSequence { seq_id: u64 }, + /// The blocks are allocated but their K/V is not computed yet. + NotReady { seq_id: u64, state: PrefillState }, + /// The completion fence fired for a table that never had a prefill issued. + FenceWithoutPending { seq_id: u64, state: PrefillState }, +} + +impl std::fmt::Display for PrefillGateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PrefillGateError::UnknownSequence { seq_id } => { + write!(f, "prefill gate: sequence {} has no block table", seq_id) + } + PrefillGateError::NotReady { seq_id, state } => write!( + f, + "prefill gate: sequence {} blocks are {:?}, not PrefillReady; refusing to share or decode", + seq_id, state + ), + PrefillGateError::FenceWithoutPending { seq_id, state } => write!( + f, + "prefill gate: completion fence for sequence {} in state {:?} without a pending prefill", + seq_id, state + ), + } + } +} + +impl std::error::Error for PrefillGateError {} + #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct BlockTable { pub sequence_id: u64, pub block_ids: Vec<BlockId>, pub total_tokens: usize, + /// Whether the K/V behind `block_ids` has been computed. Defaults to + /// `Allocated` (also for tables serialized before this field existed). + #[serde(default)] + pub prefill_state: PrefillState, +} + +impl BlockTable { + /// True only when a completed prefill computed this table's prompt K/V. + pub fn is_prefill_ready(&self) -> bool { + self.prefill_state.is_ready() + } } #[derive(Debug, Clone)] @@ -948,18 +1022,91 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { assigned.push(blk); } + // Allocation reserves and zeroes blocks only. No K/V is computed here, + // so the table starts Allocated; only the prefill completion fence + // (`complete_prefill`) may mark it PrefillReady. + let prefill_state = if cfg!(feature = "prefill_mutant_ready_at_alloc") { + PrefillState::PrefillReady + } else { + PrefillState::Allocated + }; + self.sequence_tables.insert( seq_id, BlockTable { sequence_id: seq_id, block_ids: assigned.clone(), total_tokens: num_tokens, + prefill_state, }, ); Ok(assigned) } + /// Readiness of a sequence's K/V, or None when it has no block table. + pub fn prefill_state(&self, seq_id: u64) -> Option<PrefillState> { + self.sequence_tables.get(&seq_id).map(|t| t.prefill_state) + } + + /// Records that a model prefill over the prompt span has been issued. + /// A ready table stays ready (its prefix K/V is already computed). + pub fn mark_prefill_pending(&mut self, seq_id: u64) -> Result<(), PrefillGateError> { + let table = self + .sequence_tables + .get_mut(&seq_id) + .ok_or(PrefillGateError::UnknownSequence { seq_id })?; + if !table.prefill_state.is_ready() { + table.prefill_state = PrefillState::PrefillPending; + } + Ok(()) + } + + /// The prefill completion fence: the ONLY setter of `PrefillReady`. + /// Call it only after the backend forward over the whole prompt span + /// returned Ok (aien-scheduler `AienScheduler::step` after + /// `execute_step`, and `AienScheduler::prefill_detached`). Refuses a table + /// that never had a prefill issued, so allocation alone can never become + /// ready through this path. + pub fn complete_prefill(&mut self, seq_id: u64) -> Result<(), PrefillGateError> { + let table = self + .sequence_tables + .get_mut(&seq_id) + .ok_or(PrefillGateError::UnknownSequence { seq_id })?; + match table.prefill_state { + PrefillState::PrefillPending => { + table.prefill_state = PrefillState::PrefillReady; + Ok(()) + } + PrefillState::PrefillReady | PrefillState::SharedFrozen => Ok(()), + state @ PrefillState::Allocated => { + Err(PrefillGateError::FenceWithoutPending { seq_id, state }) + } + } + } + + /// Gated zero-copy fork: shares the parent's blocks only when the parent + /// K/V is computed (PrefillReady or SharedFrozen). Refuses with a typed + /// error otherwise, so a branch can never share allocated-but-uncomputed + /// blocks. On success parent and child are both SharedFrozen. + pub fn fork_prefilled( + &mut self, + parent_id: u64, + child_id: u64, + ) -> Result<Vec<BlockId>, PrefillGateError> { + let state = self + .prefill_state(parent_id) + .ok_or(PrefillGateError::UnknownSequence { seq_id: parent_id })?; + if !state.is_ready() { + return Err(PrefillGateError::NotReady { + seq_id: parent_id, + state, + }); + } + self.fork_sequence(parent_id, child_id) + .map_err(|_| PrefillGateError::UnknownSequence { seq_id: parent_id }) + } + pub fn fork_sequence(&mut self, parent_id: u64, child_id: u64) -> Result<Vec<BlockId>, String> { let parent_table = self .sequence_tables @@ -972,12 +1119,26 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { self.blocks[blk_id].is_shared = true; } + // Readiness travels with the blocks: a fork of a ready parent freezes + // the shared prefix; a fork of an unready parent stays unready, so the + // scheduler will not decode the child (use `fork_prefilled` to refuse + // such a fork outright). + let child_state = if parent_table.prefill_state.is_ready() { + if let Some(parent) = self.sequence_tables.get_mut(&parent_id) { + parent.prefill_state = PrefillState::SharedFrozen; + } + PrefillState::SharedFrozen + } else { + parent_table.prefill_state + }; + self.sequence_tables.insert( child_id, BlockTable { sequence_id: child_id, block_ids: parent_table.block_ids.clone(), total_tokens: parent_table.total_tokens, + prefill_state: child_state, }, ); @@ -1630,4 +1791,92 @@ mod tests { mgr.commit(res2).unwrap(); assert_eq!(mgr.get_block_table(1).unwrap().total_tokens, 21); } + + // PREFILL-GATE: allocated != computed. + + #[test] + fn test_prefill_gate_allocation_is_not_ready() { + let mut mgr = AienKvManager::new(16, 16); + mgr.allocate_sequence(7, &[1, 2, 3, 4]).unwrap(); + assert_eq!(mgr.prefill_state(7), Some(PrefillState::Allocated)); + assert!( + !mgr.get_block_table(7).unwrap().is_prefill_ready(), + "allocate_sequence zeroes blocks only; it must never yield a ready table" + ); + } + + #[test] + fn test_prefill_gate_fork_refuses_unready_root() { + let mut mgr = AienKvManager::new(16, 16); + mgr.allocate_sequence(1, &[1, 2, 3]).unwrap(); + let free_before = mgr.free_block_count(); + + let err = mgr.fork_prefilled(1, 2).unwrap_err(); + assert_eq!( + err, + PrefillGateError::NotReady { + seq_id: 1, + state: PrefillState::Allocated + } + ); + assert!( + mgr.get_block_table(2).is_none(), + "refused fork must not create a child table" + ); + assert_eq!(mgr.free_block_count(), free_before); + + mgr.mark_prefill_pending(1).unwrap(); + let err = mgr.fork_prefilled(1, 2).unwrap_err(); + assert_eq!( + err, + PrefillGateError::NotReady { + seq_id: 1, + state: PrefillState::PrefillPending + } + ); + assert_eq!( + mgr.fork_prefilled(99, 2).unwrap_err(), + PrefillGateError::UnknownSequence { seq_id: 99 } + ); + } + + #[test] + fn test_prefill_gate_fence_requires_pending_then_shares_frozen() { + let mut mgr = AienKvManager::new(16, 16); + mgr.allocate_sequence(1, &[1, 2, 3]).unwrap(); + + // The fence cannot be fired on a table that never had a prefill issued. + assert_eq!( + mgr.complete_prefill(1).unwrap_err(), + PrefillGateError::FenceWithoutPending { + seq_id: 1, + state: PrefillState::Allocated + } + ); + assert_eq!(mgr.prefill_state(1), Some(PrefillState::Allocated)); + + mgr.mark_prefill_pending(1).unwrap(); + assert_eq!(mgr.prefill_state(1), Some(PrefillState::PrefillPending)); + mgr.complete_prefill(1).unwrap(); + assert_eq!(mgr.prefill_state(1), Some(PrefillState::PrefillReady)); + + let blocks = mgr.fork_prefilled(1, 2).unwrap(); + assert_eq!(blocks, mgr.get_block_table(1).unwrap().block_ids); + assert_eq!(mgr.prefill_state(1), Some(PrefillState::SharedFrozen)); + assert_eq!(mgr.prefill_state(2), Some(PrefillState::SharedFrozen)); + assert!(mgr.get_block_table(2).unwrap().is_prefill_ready()); + + // Reclaimed = table gone. + mgr.free_sequence(2).unwrap(); + assert_eq!(mgr.prefill_state(2), None); + } + + #[test] + fn test_prefill_gate_plain_fork_of_unready_parent_stays_unready() { + let mut mgr = AienKvManager::new(16, 16); + mgr.allocate_sequence(1, &[1, 2, 3]).unwrap(); + mgr.fork_sequence(1, 2).unwrap(); + assert_eq!(mgr.prefill_state(2), Some(PrefillState::Allocated)); + assert!(!mgr.get_block_table(2).unwrap().is_prefill_ready()); + } } diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 77293c17..1d58b84b 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -136,10 +136,25 @@ impl AienRuntimeSpine { ) -> Result<Option<StepMetrics>, String> { self.step_counter += 1; + // PREFILL-GATE: run the model prefill over each pending swarm root + // prompt BEFORE any branch can be scheduled, then share the computed + // root blocks with the branches. Branches never see root blocks that + // have not passed the completion fence. + let root_prefill_tokens = self.prefill_pending_swarm_roots(backend).await?; + // Execute scheduler step via backend let step_result = self.scheduler.step(backend).await?; - if let Some((outputs, metrics)) = step_result { + if step_result.is_none() && root_prefill_tokens > 0 { + return Ok(Some(StepMetrics { + prefill_tokens_processed: root_prefill_tokens, + active_kv_blocks: self.kv_manager.read().allocated_block_count(), + ..StepMetrics::default() + })); + } + + if let Some((outputs, mut metrics)) = step_result { + metrics.prefill_tokens_processed += root_prefill_tokens; // Generational SequenceId validation on step completion for output in &outputs { match output { @@ -179,7 +194,32 @@ impl AienRuntimeSpine { } } + /// Prefills every pending swarm root through the scheduler's completion + /// fence and, once the root is PrefillReady, shares its blocks with the + /// branches. Returns the number of root prompt tokens prefilled. + async fn prefill_pending_swarm_roots<B: AienInferenceBackend>( + &mut self, + backend: &mut B, + ) -> Result<usize, String> { + let mut prefilled = 0usize; + for (swarm_id, root_kv_id, prompt) in self.swarm_manager.pending_root_prefills() { + if let Some(m) = self + .scheduler + .prefill_detached(backend, root_kv_id, &prompt) + .await? + { + prefilled += m.prefill_tokens_processed; + } + let mut kv = self.kv_manager.write(); + self.swarm_manager + .fork_branches_from_ready_root(swarm_id, &mut self.arena, &mut kv)?; + } + Ok(prefilled) + } + /// Launches a swarm of agents sharing an immutable root World and physical KV blocks. + /// Branch KV is shared from the root only after the root prompt prefill + /// completes (next `step`); until then branches cannot be decoded. pub fn launch_swarm( &mut self, config: SwarmConfig, diff --git a/crates/aien-runtime/src/swarm.rs b/crates/aien-runtime/src/swarm.rs index 7ca3b144..cdd88fcf 100644 --- a/crates/aien-runtime/src/swarm.rs +++ b/crates/aien-runtime/src/swarm.rs @@ -3,7 +3,7 @@ use crate::sequence::{SequenceArena, SequenceId, SequenceState}; use crate::world::WorldStore; -use aien_kv_cache::AienKvManager; +use aien_kv_cache::{AienKvManager, PrefillGateError}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -46,6 +46,10 @@ pub struct SwarmRecord { pub struct SwarmManager { swarms: HashMap<u64, SwarmRecord>, next_swarm_id: u64, + /// PREFILL-GATE: swarms whose root prompt has not been prefilled yet + /// (swarm id -> root prompt). Branch KV is forked from the root only after + /// the root's prefill completion fence; see `fork_branches_from_ready_root`. + pending_root_prefill: HashMap<u64, Vec<u32>>, } impl Default for SwarmManager { @@ -59,6 +63,7 @@ impl SwarmManager { Self { swarms: HashMap::new(), next_swarm_id: 1, + pending_root_prefill: HashMap::new(), } } @@ -90,28 +95,35 @@ impl SwarmManager { timestamp, )?; - // 2. Allocate root prompt tokens in physical KV manager + // 2. Allocate root prompt blocks in physical KV manager. This reserves + // and zeroes blocks only (PrefillState::Allocated); no K/V is computed. let root_u64 = root_seq.as_u64(); kv.allocate_sequence(root_u64, prompt_tokens)?; if let Some(record) = arena.get_mut(root_seq) { - record.prefill_cursor = prompt_tokens.len(); + // Nothing is prefilled yet: the cursor advances at the completion fence. + record.prefill_cursor = 0; record.state = SequenceState::Prefill; } - // 3. Atomically fork N branches sharing the root World and root KV blocks + // 3. Fork N branch records and worlds. Branch KV is NOT forked here: + // the root blocks are not computed, and sharing them would let branches + // decode over zeroed K/V. `fork_branches_from_ready_root` shares the + // root blocks after the root prefill completion fence. let mut branch_sequences = Vec::with_capacity(config.branch_count); let mut branch_worlds = Vec::with_capacity(config.branch_count); for _ in 0..config.branch_count { let child_world = world_store.fork_world(root_world_id, timestamp)?; let child_seq = arena.fork(root_seq, child_world, timestamp)?; - let child_u64 = child_seq.as_u64(); - - // Zero-copy KV fork: increments refcount on parent physical blocks - kv.fork_sequence(root_u64, child_u64)?; + if let Some(child) = arena.get_mut(child_seq) { + // Waiting on the root prefill, not decoding. + child.state = SequenceState::Prefill; + } branch_sequences.push(child_seq); branch_worlds.push(child_world); } + self.pending_root_prefill + .insert(swarm_id, prompt_tokens.to_vec()); let record = SwarmRecord { id: swarm_id, @@ -132,6 +144,75 @@ impl SwarmManager { self.swarms.get(&swarm_id) } + /// Swarms whose root prompt still needs a model prefill: + /// (swarm id, root KV sequence id, root prompt). + pub fn pending_root_prefills(&self) -> Vec<(u64, u64, Vec<u32>)> { + let mut pending: Vec<(u64, u64, Vec<u32>)> = self + .pending_root_prefill + .iter() + .filter_map(|(&swarm_id, prompt)| { + self.swarms + .get(&swarm_id) + .filter(|s| s.state == SwarmState::Running) + .map(|s| (swarm_id, s.root_sequence_id.as_u64(), prompt.clone())) + }) + .collect(); + pending.sort_by_key(|p| p.0); + pending + } + + /// True while the swarm's root prompt has not passed its prefill fence. + pub fn is_root_prefill_pending(&self, swarm_id: u64) -> bool { + self.pending_root_prefill.contains_key(&swarm_id) + } + + /// Shares the root KV blocks with every branch once the root prefill + /// completion fence has fired. Refuses (typed `PrefillGateError`, as a + /// String) while the root is not PrefillReady; nothing is forked then. + pub fn fork_branches_from_ready_root( + &mut self, + swarm_id: u64, + arena: &mut SequenceArena, + kv: &mut AienKvManager, + ) -> Result<(), String> { + let swarm = self + .swarms + .get(&swarm_id) + .ok_or_else(|| format!("Swarm {} not found", swarm_id))?; + let root_u64 = swarm.root_sequence_id.as_u64(); + + // Check readiness once up front so a refusal forks nothing. + match kv.prefill_state(root_u64) { + Some(state) if state.is_ready() => {} + Some(state) => { + return Err(PrefillGateError::NotReady { + seq_id: root_u64, + state, + } + .to_string()) + } + None => return Err(PrefillGateError::UnknownSequence { seq_id: root_u64 }.to_string()), + } + + let prompt_len = kv + .get_block_table(root_u64) + .map(|t| t.total_tokens) + .unwrap_or(0); + for &child in &swarm.branch_sequences { + kv.fork_prefilled(root_u64, child.as_u64()) + .map_err(|e| e.to_string())?; + if let Some(rec) = arena.get_mut(child) { + rec.prefill_cursor = prompt_len; + rec.state = SequenceState::Decode; + } + } + if let Some(root) = arena.get_mut(swarm.root_sequence_id) { + root.prefill_cursor = prompt_len; + } + self.pending_root_prefill.remove(&swarm_id); + Ok(()) + } + /// Cancels a swarm and reclaims its resources: KV sequences, arena slots, /// and branch worlds. The root world is retained; branch worlds are dropped. pub fn cancel_swarm( @@ -145,6 +226,7 @@ impl SwarmManager { .swarms .get_mut(&swarm_id) .ok_or_else(|| format!("Swarm {} not found", swarm_id))?; + self.pending_root_prefill.remove(&swarm_id); swarm.state = SwarmState::Cancelling; @@ -212,6 +294,7 @@ impl SwarmManager { } let _ = kv.free_sequence(swarm.root_sequence_id.as_u64()); arena.free(swarm.root_sequence_id); + self.pending_root_prefill.remove(&swarm_id); for world_id in swarm.branch_worlds.clone() { worlds.drop_world(world_id); @@ -308,4 +391,61 @@ mod tests { "root arena slot must be reclaimed on natural completion" ); } + + #[test] + fn prefill_gate_branches_do_not_share_uncomputed_root_blocks() { + let mut arena = SequenceArena::new(256); + let kv_shared = aien_kv_cache::create_shared_kv_manager(256, 16); + let mut kv = kv_shared.write(); + let mut worlds = WorldStore::new(); + let mut manager = SwarmManager::new(); + + let prompt = vec![4u32, 5, 6, 7]; + let swarm_id = manager + .launch_swarm(test_config(3), &mut arena, &mut kv, &mut worlds, &prompt, 1) + .expect("swarm launch must succeed"); + let record = manager.get_swarm(swarm_id).expect("record").clone(); + let root = record.root_sequence_id.as_u64(); + + assert!(manager.is_root_prefill_pending(swarm_id)); + assert_eq!( + kv.prefill_state(root), + Some(aien_kv_cache::PrefillState::Allocated), + "launch allocates root blocks; it computes nothing" + ); + for child in &record.branch_sequences { + assert!( + kv.get_block_table(child.as_u64()).is_none(), + "no branch may hold root blocks before the root prefill fence" + ); + } + + // Typed refusal while the root is not PrefillReady; nothing is forked. + let err = manager + .fork_branches_from_ready_root(swarm_id, &mut arena, &mut kv) + .unwrap_err(); + assert!( + err.contains("not PrefillReady"), + "unexpected error: {}", + err + ); + for child in &record.branch_sequences { + assert!(kv.get_block_table(child.as_u64()).is_none()); + } + assert!(manager.is_root_prefill_pending(swarm_id)); + + // After the completion fence, branches share the frozen root blocks. + kv.mark_prefill_pending(root).unwrap(); + kv.complete_prefill(root).unwrap(); + manager + .fork_branches_from_ready_root(swarm_id, &mut arena, &mut kv) + .expect("fork after fence"); + assert!(!manager.is_root_prefill_pending(swarm_id)); + let root_blocks = kv.get_block_table(root).unwrap().block_ids.clone(); + for child in &record.branch_sequences { + let table = kv.get_block_table(child.as_u64()).expect("branch table"); + assert_eq!(table.block_ids, root_blocks); + assert!(table.is_prefill_ready()); + } + } } diff --git a/crates/aien-runtime/tests/swarm_prefill_gate_test.rs b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs new file mode 100644 index 00000000..be953371 --- /dev/null +++ b/crates/aien-runtime/tests/swarm_prefill_gate_test.rs @@ -0,0 +1,158 @@ +//! PREFILL-GATE end to end: a launched swarm must run the root prompt through +//! the model before any branch decodes. +//! +//! Uses only APIs that already exist on main (cfd9982), so this file also runs +//! against main, where it must FAIL (see scripts/prefill-gate/fails-on-main.sh): +//! on main SwarmManager::launch_swarm forks branches from allocated-but-zeroed +//! root blocks (crates/aien-runtime/src/swarm.rs:95-111 at cfd9982) and the +//! scheduler decodes them with no prefill at all. +//! +//! The stock MockInferenceBackend ignores prompt content, so this test uses a +//! recording backend that logs every prefill span and every decode, in order. + +use std::collections::HashMap; + +use aien_inference_abi::{ + AienInferenceBackend, DecodeOutput, ModelConfig, ScheduledBatch, StepMetrics, +}; +use aien_kv_cache::create_shared_kv_manager; +use aien_runtime::spine::AienRuntimeSpine; +use aien_runtime::swarm::SwarmConfig; +use aien_scheduler::SchedulerConfig; +use async_trait::async_trait; + +#[derive(Debug, Clone)] +enum Event { + Prefill { id: u64, tokens: Vec<u32> }, + Decode { id: u64 }, +} + +#[derive(Default)] +struct RecordingBackend { + events: Vec<Event>, +} + +#[async_trait] +impl AienInferenceBackend for RecordingBackend { + async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> { + Ok(()) + } + + async fn execute_step( + &mut self, + batch: &ScheduledBatch, + ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> { + let mut outputs = Vec::new(); + let mut prefill_tokens = 0; + for req in &batch.prefill_requests { + prefill_tokens += req.prompt_tokens.len(); + self.events.push(Event::Prefill { + id: req.request_id, + tokens: req.prompt_tokens.clone(), + }); + outputs.push(DecodeOutput::Token { + request_id: req.request_id, + token_id: 100, + logprob: None, + }); + } + for &id in &batch.decode_requests { + self.events.push(Event::Decode { id }); + outputs.push(DecodeOutput::Token { + request_id: id, + token_id: 101, + logprob: None, + }); + } + let metrics = StepMetrics { + prefill_tokens_processed: prefill_tokens, + decode_tokens_emitted: batch.decode_requests.len() + batch.prefill_requests.len(), + step_latency_us: 0, + active_kv_blocks: batch.block_tables.values().map(|v| v.len()).sum(), + }; + Ok((outputs, metrics)) + } +} + +#[tokio::test] +async fn prefill_gate_swarm_branches_never_decode_before_root_prompt_prefill() { + let kv_manager = create_shared_kv_manager(256, 16); + let sched_cfg = SchedulerConfig { + max_batch_size: 32, + max_batch_tokens: 2048, + max_prefill_tokens: 1024, + prefill_chunk_size: 16, + chunk_prefill: true, + watermark_blocks: 4, + }; + let mut spine = AienRuntimeSpine::new(64, sched_cfg, kv_manager.clone()); + let mut backend = RecordingBackend::default(); + + let prompt: Vec<u32> = (500..540).collect(); + let branch_count = 4usize; + let config = SwarmConfig { + model_handle: 1, + branch_count, + max_active_sequences: branch_count, + max_tokens_per_branch: 3, + root_world_id: 0, + priority: 1, + }; + let swarm_id = spine.launch_swarm(config, &prompt).expect("launch"); + let swarm = spine + .swarm_manager + .get_swarm(swarm_id) + .expect("swarm record") + .clone(); + let root = swarm.root_sequence_id.as_u64(); + let branches: Vec<u64> = swarm.branch_sequences.iter().map(|s| s.as_u64()).collect(); + + let mut steps = 0; + while (spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0) + && steps < 100 + { + steps += 1; + spine.step(&mut backend).await.expect("step"); + } + + // Replay the backend log in order. Every branch decode must come after + // the full prompt was run through the model, for the shared root or for + // that branch itself. + let mut prefilled: HashMap<u64, Vec<u32>> = HashMap::new(); + let mut branch_decodes = 0usize; + let covers_prompt = |seen: Option<&Vec<u32>>| { + seen.map(|s| s.len() >= prompt.len() && s[..prompt.len()] == prompt[..]) + .unwrap_or(false) + }; + for event in &backend.events { + match event { + Event::Prefill { id, tokens } => { + prefilled.entry(*id).or_default().extend_from_slice(tokens); + } + Event::Decode { id } => { + if branches.contains(id) { + branch_decodes += 1; + assert!( + covers_prompt(prefilled.get(&root)) || covers_prompt(prefilled.get(id)), + "PREFILL_GATE_VIOLATION: branch {} decoded before its prompt was prefilled \ + (root prefilled {:?} tokens, branch prefilled {:?} tokens, prompt {} tokens)", + id, + prefilled.get(&root).map(|v| v.len()), + prefilled.get(id).map(|v| v.len()), + prompt.len() + ); + } + } + } + } + + assert!( + branch_decodes > 0, + "branches must decode once the root prompt is prefilled" + ); + assert_eq!( + spine.scheduler.metrics().finished_requests as usize, + branch_count, + "every branch must finish" + ); +} diff --git a/crates/aien-scheduler/Cargo.toml b/crates/aien-scheduler/Cargo.toml index dfec6375..62017198 100644 --- a/crates/aien-scheduler/Cargo.toml +++ b/crates/aien-scheduler/Cargo.toml @@ -25,3 +25,10 @@ path = "src/bin/bench_inference_stack.rs" [[bin]] name = "stress_aien_live" path = "src/bin/stress_aien_live.rs" + +[features] +# MUTANT ONLY (PREFILL-GATE). Never enable in a real build. Removes the +# scheduler's prefill readiness check so allocated-but-uncomputed block tables +# are decoded. The prefill-gate tests must FAIL with this feature on; see +# scripts/prefill-gate/mutant.sh. +prefill_mutant_no_check = [] diff --git a/crates/aien-scheduler/src/lib.rs b/crates/aien-scheduler/src/lib.rs index bf4549d9..c39464e7 100644 --- a/crates/aien-scheduler/src/lib.rs +++ b/crates/aien-scheduler/src/lib.rs @@ -6,7 +6,7 @@ pub use sequence::*; use aien_inference_abi::{ AienInferenceBackend, DecodeOutput, FinishReason, ScheduledBatch, SequenceRequest, StepMetrics, }; -use aien_kv_cache::AienKvManager; +use aien_kv_cache::{AienKvManager, PrefillGateError}; use aien_platform::{InferenceWork, Priority}; use parking_lot::RwLock; use serde::{Deserialize, Serialize}; @@ -14,6 +14,19 @@ use std::collections::{HashMap, VecDeque}; use std::sync::Arc; use std::time::Instant; +/// Prefill readiness gate (PREFILL-GATE). A sequence may enter decode only +/// when its block table K/V was computed by a completed prefill +/// (`BlockTable::is_prefill_ready`). Having a block table is not enough: +/// `allocate_sequence` only reserves and zeroes blocks. +#[inline] +fn prefill_gate_allows_decode(table_ready: bool) -> bool { + if cfg!(feature = "prefill_mutant_no_check") { + // MUTANT: readiness check removed. Tests must catch this. + return true; + } + table_ready +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SchedulerConfig { pub max_batch_size: usize, @@ -353,6 +366,7 @@ impl AienScheduler { // 2. Schedule active decode sequences and in-flight prefill chunks let mut running_ids = self.running_sequences.clone(); running_ids.sort(); + let mut needs_prefill: Vec<SequenceId> = Vec::new(); for seq_id in running_ids { if decode_requests.len() + prefill_requests.len() >= self.config.max_batch_size { @@ -368,11 +382,25 @@ impl AienScheduler { }; if seq.is_prefilled { - // Active decode step - if let Some(table) = self.kv_manager.read().get_block_table(seq_id.to_u64()) { - block_tables.insert(seq_id.to_u64(), table.block_ids.clone()); - decode_requests.push(seq_id.to_u64()); - current_tokens += 1; + // Active decode step, gated on computed K/V (PREFILL-GATE). + let table_state = self + .kv_manager + .read() + .get_block_table(seq_id.to_u64()) + .map(|t| (t.block_ids.clone(), t.is_prefill_ready())); + 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; + } else { + // The table exists but its K/V was never computed: + // send the sequence back for a real prefill, never decode. + seq.is_prefilled = false; + seq.prompt_tokens_prefilled = 0; + seq.phase = SequencePhase::Waiting; + needs_prefill.push(seq_id); + } } } else { // Continuing chunked prefill @@ -405,6 +433,14 @@ impl AienScheduler { } } + // 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 { + 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); + } + // 3. Admit waiting or preempted requests if capacity permits and not under preemption pressure if !preempted_this_step { while decode_requests.len() + prefill_requests.len() < self.config.max_batch_size @@ -473,22 +509,32 @@ impl AienScheduler { let chunk_size = std::cmp::min(chunk_size, prefill_budget); // Scheduler Zero-Copy Fork Invariant: Sequence admission must inspect existing block tables in KvCache. - // Pre-forked branches with assigned prefix blocks skip fresh block allocation and enter decode directly without redundant prefill. + // Pre-forked branches skip redundant prefill and enter decode directly ONLY when the + // shared prefix K/V was computed by a completed prefill (PREFILL-GATE). A block table + // alone proves allocation, not computation: allocate_sequence only reserves and zeroes. let existing_table = self .kv_manager .read() .get_block_table(next_seq_id.to_u64()) - .map(|t| t.block_ids.clone()); - - if let Some(blocks) = existing_table { - block_tables.insert(next_seq_id.to_u64(), blocks); - seq.is_prefilled = true; - seq.phase = SequencePhase::Decode; - seq.prompt_tokens_prefilled = prompt_len; - decode_requests.push(next_seq_id.to_u64()); - current_tokens += 1; - self.running_sequences.push(next_seq_id); - continue; + .map(|t| (t.block_ids.clone(), t.is_prefill_ready())); + + match existing_table { + Some((blocks, ready)) if prefill_gate_allows_decode(ready) => { + block_tables.insert(next_seq_id.to_u64(), blocks); + seq.is_prefilled = true; + seq.phase = SequencePhase::Decode; + seq.prompt_tokens_prefilled = prompt_len; + decode_requests.push(next_seq_id.to_u64()); + current_tokens += 1; + self.running_sequences.push(next_seq_id); + continue; + } + Some(_) => { + // Allocated but not computed: drop the table (and its share of + // any parent blocks) and fall through to allocate + prefill. + let _ = self.kv_manager.write().free_sequence(next_seq_id.to_u64()); + } + None => {} } if chunk_size == 0 { @@ -505,6 +551,10 @@ impl AienScheduler { .kv_manager .write() .allocate_sequence(next_seq_id.to_u64(), &seq.prompt)?; + self.kv_manager + .write() + .mark_prefill_pending(next_seq_id.to_u64()) + .map_err(|e| e.to_string())?; block_tables.insert(next_seq_id.to_u64(), assigned_blocks); @@ -583,6 +633,90 @@ impl AienScheduler { })) } + /// Runs a model prefill over `prompt` for a KV sequence this scheduler does + /// not own (a swarm root, which is never decoded), then fires the + /// completion fence. The prompt is sent in chunks of `prefill_chunk_size` + /// (capped by `max_prefill_tokens`). PrefillReady is set only after every + /// chunk's `execute_step` returned Ok and the backend reported processing + /// the whole chunk; any error leaves the table not ready. + /// + /// Returns Ok(None) when the table is already ready (nothing to compute), + /// Ok(Some(metrics)) after a completed prefill. + pub async fn prefill_detached( + &mut self, + backend: &mut (dyn AienInferenceBackend + '_), + kv_seq_id: u64, + prompt: &[u32], + ) -> Result<Option<StepMetrics>, String> { + let blocks = { + let mut kv = self.kv_manager.write(); + if kv.get_block_table(kv_seq_id).is_none() { + kv.allocate_sequence(kv_seq_id, prompt)?; + } + let table = kv.get_block_table(kv_seq_id).ok_or_else(|| { + PrefillGateError::UnknownSequence { seq_id: kv_seq_id }.to_string() + })?; + if table.is_prefill_ready() { + return Ok(None); + } + let blocks = table.block_ids.clone(); + kv.mark_prefill_pending(kv_seq_id) + .map_err(|e| e.to_string())?; + blocks + }; + + let chunk_len = self + .config + .prefill_chunk_size + .min(self.config.max_prefill_tokens) + .max(1); + let t0 = Instant::now(); + let mut prefill_tokens = 0usize; + + for span in prompt.chunks(chunk_len) { + self.step_id += 1; + let mut block_tables = HashMap::new(); + block_tables.insert(kv_seq_id, blocks.clone()); + let batch = ScheduledBatch { + prefill_requests: vec![SequenceRequest { + request_id: kv_seq_id, + prompt_tokens: span.to_vec(), + sampling_params: aien_inference_abi::SamplingParams::default(), + arrival_time_ns: 0, + priority: Priority::Normal as u8, + }], + decode_requests: Vec::new(), + block_tables, + step_id: self.step_id, + }; + let (_outputs, metrics) = backend.execute_step(&batch).await?; + if metrics.prefill_tokens_processed < span.len() { + return Err(format!( + "prefill gate: backend processed {} of {} prompt tokens for sequence {}; not marking ready", + metrics.prefill_tokens_processed, + span.len(), + kv_seq_id + )); + } + prefill_tokens += span.len(); + } + + // PREFILL-GATE completion fence: the forward over the whole prompt span completed. + self.kv_manager + .write() + .complete_prefill(kv_seq_id) + .map_err(|e| e.to_string())?; + + self.metrics.total_prefill_tokens += prefill_tokens as u64; + let active_kv_blocks = self.kv_manager.read().allocated_block_count(); + Ok(Some(StepMetrics { + prefill_tokens_processed: prefill_tokens, + decode_tokens_emitted: 0, + step_latency_us: t0.elapsed().as_micros() as u64, + active_kv_blocks, + })) + } + /// Advances the engine by one step using the configured backend. pub async fn step( &mut self, @@ -606,6 +740,12 @@ impl AienScheduler { if seq.prompt_tokens_prefilled >= seq.prompt.len() { seq.is_prefilled = true; seq.phase = SequencePhase::Decode; + // PREFILL-GATE completion fence: execute_step returned Ok + // for the final prompt chunk, so the K/V is computed. + let _ = self + .kv_manager + .write() + .complete_prefill(prefill_req.request_id); } } } @@ -924,4 +1064,115 @@ mod tests { assert_eq!(scheduler.preempted_count(), 1); assert_eq!(scheduler.running_count(), 1); } + + // PREFILL-GATE unit tests (new readiness API). + + fn gate_request(request_id: u64, prompt: Vec<u32>, max_tokens: usize) -> SequenceRequest { + SequenceRequest { + request_id, + prompt_tokens: prompt, + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens, + stop_token_ids: vec![], + }, + arrival_time_ns: 0, + priority: 1, + } + } + + #[tokio::test] + async fn test_prefill_gate_scheduler_fence_marks_ready_only_after_last_chunk() { + let kv_manager = create_shared_kv_manager(100, 16); + let config = SchedulerConfig { + max_batch_size: 16, + max_batch_tokens: 1024, + max_prefill_tokens: 512, + prefill_chunk_size: 64, + chunk_prefill: true, + watermark_blocks: 2, + }; + let mut scheduler = AienScheduler::new(config, kv_manager.clone()); + let mut backend = MockInferenceBackend::new(0); + + let seq = scheduler.submit_request(gate_request(0, (0..128).collect(), 2)); + let id = seq.to_u64(); + + // Chunk 1 of 2: prefill issued, not complete. + scheduler.step(&mut backend).await.unwrap().unwrap(); + assert_eq!( + kv_manager.read().prefill_state(id), + Some(aien_kv_cache::PrefillState::PrefillPending), + "a half-prefilled table must not be ready" + ); + + // Chunk 2 of 2: completion fence fires. + scheduler.step(&mut backend).await.unwrap().unwrap(); + assert_eq!( + kv_manager.read().prefill_state(id), + Some(aien_kv_cache::PrefillState::PrefillReady) + ); + + let res3 = scheduler.step(&mut backend).await.unwrap().unwrap(); + assert_eq!(res3.1.decode_tokens_emitted, 1); + } + + #[test] + fn test_prefill_gate_ready_fork_enters_decode_directly() { + // Positive control: a branch forked from a computed root decodes + // without redundant prefill. The gate is not "never decode". + let kv_manager = create_shared_kv_manager(64, 16); + let mut scheduler = AienScheduler::new(SchedulerConfig::default(), kv_manager.clone()); + + let root = SequenceId::new(1, 1).unwrap().to_u64(); + let child = SequenceId::new(2, 1).unwrap().to_u64(); + let prompt: Vec<u32> = (0..20).collect(); + { + let mut kv = kv_manager.write(); + kv.allocate_sequence(root, &prompt).unwrap(); + kv.mark_prefill_pending(root).unwrap(); + kv.complete_prefill(root).unwrap(); + kv.fork_prefilled(root, child).unwrap(); + } + + scheduler.submit_request(gate_request(child, prompt, 4)); + let batch = scheduler.build_scheduled_batch().unwrap().unwrap(); + assert!(batch.decode_requests.contains(&child)); + assert!(batch.prefill_requests.is_empty()); + } + + #[tokio::test] + async fn test_prefill_gate_running_sequence_with_unready_table_is_reprefilled() { + let kv_manager = create_shared_kv_manager(64, 16); + let mut scheduler = AienScheduler::new(SchedulerConfig::default(), kv_manager.clone()); + let mut backend = MockInferenceBackend::new(0); + + let prompt: Vec<u32> = vec![1, 2, 3, 4]; + let seq = scheduler.submit_request(gate_request(0, prompt.clone(), 8)); + let id = seq.to_u64(); + scheduler.step(&mut backend).await.unwrap().unwrap(); + assert!(kv_manager + .read() + .get_block_table(id) + .unwrap() + .is_prefill_ready()); + + // Counterexample: the running sequence's table is replaced by an + // allocated-but-uncomputed one. It must be prefilled again, not decoded. + { + let mut kv = kv_manager.write(); + kv.free_sequence(id).unwrap(); + kv.allocate_sequence(id, &prompt).unwrap(); + } + let batch = scheduler.build_scheduled_batch().unwrap().unwrap(); + assert!( + !batch.decode_requests.contains(&id), + "PREFILL_GATE_VIOLATION: running sequence decoded over an uncomputed table" + ); + assert!(batch + .prefill_requests + .iter() + .any(|r| r.request_id == id && r.prompt_tokens == prompt)); + } } diff --git a/crates/aien-scheduler/tests/prefill_gate_test.rs b/crates/aien-scheduler/tests/prefill_gate_test.rs new file mode 100644 index 00000000..ffbb0cf9 --- /dev/null +++ b/crates/aien-scheduler/tests/prefill_gate_test.rs @@ -0,0 +1,63 @@ +//! PREFILL-GATE: allocated != computed. +//! +//! Uses only APIs that already exist on main (cfd9982), so this file also runs +//! against main, where it must FAIL (see scripts/prefill-gate/fails-on-main.sh). +//! On main the admission rule (crates/aien-scheduler/src/lib.rs:475-492 at +//! cfd9982) treats any existing block table as prefilled and decodes it. + +use aien_inference_abi::{SamplingParams, SequenceRequest}; +use aien_kv_cache::create_shared_kv_manager; +use aien_scheduler::{AienScheduler, SchedulerConfig, SequenceId}; + +#[test] +fn prefill_gate_allocated_but_unprefilled_table_is_prefilled_not_decoded() { + let kv_manager = create_shared_kv_manager(64, 16); + let config = SchedulerConfig { + max_batch_size: 16, + max_batch_tokens: 1024, + max_prefill_tokens: 512, + prefill_chunk_size: 64, + chunk_prefill: true, + watermark_blocks: 2, + }; + let mut scheduler = AienScheduler::new(config, kv_manager.clone()); + + // A swarm-style branch id (slot > 0) whose blocks were allocated and + // zeroed by allocate_sequence, but never run through the model. + let branch = SequenceId::new(3, 1).unwrap().to_u64(); + let prompt: Vec<u32> = (10..50).collect(); + kv_manager + .write() + .allocate_sequence(branch, &prompt) + .expect("allocate"); + + scheduler.submit_request(SequenceRequest { + request_id: branch, + prompt_tokens: prompt.clone(), + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 4, + stop_token_ids: vec![], + }, + arrival_time_ns: 0, + priority: 1, + }); + + let batch = scheduler + .build_scheduled_batch() + .expect("schedule") + .expect("non-empty batch"); + + assert!( + !batch.decode_requests.contains(&branch), + "PREFILL_GATE_VIOLATION: sequence with allocated-but-uncomputed KV blocks was scheduled for decode" + ); + assert!( + batch + .prefill_requests + .iter() + .any(|r| r.request_id == branch && r.prompt_tokens == prompt), + "PREFILL_GATE_VIOLATION: sequence with uncomputed KV blocks was not scheduled for prompt prefill" + ); +} diff --git a/scripts/prefill-gate/fails-on-main.sh b/scripts/prefill-gate/fails-on-main.sh new file mode 100755 index 00000000..4e795d00 --- /dev/null +++ b/scripts/prefill-gate/fails-on-main.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# PREFILL-GATE counterexample check (shell only). +# +# Copies the two new main-compatible test files onto a clean checkout of the +# base ref (default origin/main) and runs them there. The defect is present on +# main, so each test must FAIL with the PREFILL_GATE_VIOLATION marker. +# +# Exit 0 ONLY when every test fails on the base ref with that marker. A test +# that passes on main, or fails for another reason (build error), exits 1. +# +# The temporary worktree is created as a sibling of this checkout so the +# workspace path dependencies (../aien-protocols) resolve, and is removed on exit. +# +# Usage: bash scripts/prefill-gate/fails-on-main.sh [base-ref] +set -u + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +BASE="${1:-origin/main}" +TMP="$(dirname "$ROOT")/.prefill-gate-main-check-$$" +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target/prefill-gate-main}" + +cleanup() { + git -C "$ROOT" worktree remove --force "$TMP" >/dev/null 2>&1 + git -C "$ROOT" worktree prune >/dev/null 2>&1 +} +trap cleanup EXIT + +git -C "$ROOT" worktree add --detach "$TMP" "$BASE" >/dev/null 2>&1 || { + echo "cannot create worktree of $BASE at $TMP" + exit 2 +} + +mkdir -p "$TMP/crates/aien-scheduler/tests" "$TMP/crates/aien-runtime/tests" +cp "$ROOT/crates/aien-scheduler/tests/prefill_gate_test.rs" "$TMP/crates/aien-scheduler/tests/" +cp "$ROOT/crates/aien-runtime/tests/swarm_prefill_gate_test.rs" "$TMP/crates/aien-runtime/tests/" + +ALL_OK=1 +check() { + local pkg="$1" test="$2" log rc + log="$(mktemp -t "prefill-main-${test}-XXXXXX.log")" + (cd "$TMP" && cargo test -p "$pkg" --test "$test") >"$log" 2>&1 + rc=$? + if [ "$rc" -ne 0 ] && grep -q "PREFILL_GATE_VIOLATION" "$log"; then + echo "FAILS ON $BASE (expected): $pkg --test $test" + else + echo "UNEXPECTED on $BASE: $pkg --test $test exit $rc without PREFILL_GATE_VIOLATION. Log: $log" + tail -n 30 "$log" + ALL_OK=0 + fi +} + +check aien-scheduler prefill_gate_test +check aien-runtime swarm_prefill_gate_test + +if [ "$ALL_OK" -eq 1 ]; then + echo "PREFILL-GATE counterexample confirmed: new tests fail on $BASE" + exit 0 +fi +exit 1 diff --git a/scripts/prefill-gate/mutant.sh b/scripts/prefill-gate/mutant.sh new file mode 100755 index 00000000..4d06bb97 --- /dev/null +++ b/scripts/prefill-gate/mutant.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# PREFILL-GATE mutation check (shell only). +# +# Runs the prefill-gate tests with one mutant cargo feature switched on. The +# mutant features are off by default and exist only for this check: +# no_check aien-scheduler/prefill_mutant_no_check +# (M1: scheduler readiness check removed) +# ready_at_alloc aien-kv-cache/prefill_mutant_ready_at_alloc +# (M2: block tables marked ready at allocation, no fence) +# ready_at_alloc_e2e M2 again, caught end to end through aien-runtime +# +# Exit 0 ONLY when the mutant is caught: cargo test fails AND at least one test +# whose name contains "prefill_gate" is reported FAILED. A build error is not a +# catch and exits 1. A mutant that survives (all tests pass) exits 1. +# +# Usage: bash scripts/prefill-gate/mutant.sh no_check|ready_at_alloc|ready_at_alloc_e2e +set -u + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +MODE="${1:-}" +case "$MODE" in + no_check) + ARGS=(-p aien-scheduler --features prefill_mutant_no_check) ;; + ready_at_alloc) + ARGS=(-p aien-kv-cache --features prefill_mutant_ready_at_alloc) ;; + ready_at_alloc_e2e) + ARGS=(-p aien-runtime --features aien-kv-cache/prefill_mutant_ready_at_alloc) ;; + *) + echo "usage: $0 no_check|ready_at_alloc|ready_at_alloc_e2e" >&2 + exit 2 ;; +esac + +LOG="$(mktemp -t "prefill-mutant-${MODE}-XXXXXX.log")" +cd "$ROOT" || exit 2 +cargo test "${ARGS[@]}" --no-fail-fast >"$LOG" 2>&1 +RC=$? + +CAUGHT_RE='^test .*prefill_gate.* \.\.\. FAILED$' +if [ "$RC" -eq 0 ]; then + echo "MUTANT SURVIVED ($MODE): every test passed with the mutant on. Log: $LOG" + exit 1 +fi +if grep -Eq "$CAUGHT_RE" "$LOG"; then + echo "MUTANT CAUGHT ($MODE): cargo test exit $RC" + grep -E "$CAUGHT_RE" "$LOG" + exit 0 +fi +echo "MUTANT NOT CAUGHT BY A PREFILL GATE TEST ($MODE): cargo exit $RC with no prefill_gate test failure (build error?). Log: $LOG" +tail -n 30 "$LOG" +exit 1