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#174 (code only)
Apply it
git checkout -b patch-fb9d909a6c9f1e25 c75c583c1f1576ca2c97654eed7ca6319565d48d curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/fb9d909a6c9f1e25.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
174
bd6acd4c8c56d482ac51e0a3f18c30d91eb7252f
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":174,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/174","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:12Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index fc456044..5de53cca 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -650,51 +650,11 @@ impl NativeTransformerBackend { Self::forward_token_impl_paged(weights, backend, token_id, pos, seq_state, 0, None) } - /// How many fresh physical blocks `appends` consecutive - /// `AienKvManager::append_token_with_slot` calls on `seq_id` would - /// allocate, computed read-only from the table's tail block with the same - /// rule as aien-kv-cache `append_token_with_slot`: - /// - empty table: the first append allocates a block; - /// - shared tail block, partly filled: copy-on-write, one fresh block; - /// - shared tail block, full: one fresh block; - /// - private tail block: its free slots take appends first; - /// - /// then every further `block_size` appends need one more fresh block. - /// Returns 0 when the sequence has no block table (the append itself then - /// reports the missing sequence). + /// Fresh physical blocks `appends` consecutive appends on `seq_id` would + /// allocate. The rule lives in one place, `AienKvManager:: + /// blocks_needed_for_appends`; this only forwards to it. fn kv_blocks_needed_for_appends(kv: &AienKvManager, seq_id: u64, appends: usize) -> usize { - if appends == 0 { - return 0; - } - let Some(table) = kv.get_block_table(seq_id) else { - return 0; - }; - let block_size = kv.block_size(); - let mut remaining = appends; - let mut needed = 0usize; - // Free slots left in the tail block once the first append has resolved. - let tail_free = match table.block_ids.last().and_then(|&id| kv.get_block(id)) { - None => { - // Empty table: the first append allocates a block holding 1 token. - needed += 1; - remaining -= 1; - block_size - 1 - } - Some(blk) if blk.is_shared => { - // Copy-on-write of a partly filled tail, or a fresh block after a - // full one: either way one fresh private block takes this append. - needed += 1; - remaining -= 1; - if blk.num_tokens < block_size { - block_size - (blk.num_tokens + 1) - } else { - block_size - 1 - } - } - Some(blk) => block_size.saturating_sub(blk.num_tokens), - }; - remaining -= remaining.min(tail_free); - needed + remaining.div_ceil(block_size) + kv.blocks_needed_for_appends(seq_id, appends) } /// `Some((needed, available))` when `appends` appends to `seq_id` need more diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs index e1742983..fda9044d 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs @@ -1405,6 +1405,91 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { self.block_size } + /// Total physical blocks in the pool (free + allocated). + pub fn total_block_count(&self) -> usize { + self.total_blocks + } + + /// How many fresh physical blocks `appends` consecutive + /// `append_token_with_slot` calls on `seq_id` would allocate, computed + /// read-only from the table's tail block with the same rule as + /// `append_token_with_slot`: + /// - empty table: the first append allocates a block; + /// - shared tail block, partly filled: copy-on-write, one fresh block; + /// - shared tail block, full: one fresh block; + /// - private tail block: its free slots take appends first; + /// + /// then every further `block_size` appends need one more fresh block. + /// Returns 0 when the sequence has no block table (the append itself then + /// reports the missing sequence). + pub fn blocks_needed_for_appends(&self, seq_id: u64, appends: usize) -> usize { + if appends == 0 { + return 0; + } + let Some(table) = self.sequence_tables.get(&seq_id) else { + return 0; + }; + let block_size = self.block_size; + let mut remaining = appends; + let mut needed = 0usize; + // Free slots left in the tail block once the first append has resolved. + let tail_free = match table.block_ids.last().and_then(|&id| self.get_block(id)) { + None => { + // Empty table: the first append allocates a block holding 1 token. + needed += 1; + remaining -= 1; + block_size - 1 + } + Some(blk) if blk.is_shared => { + // Copy-on-write of a partly filled tail, or a fresh block after a + // full one: either way one fresh private block takes this append. + needed += 1; + remaining -= 1; + if blk.num_tokens < block_size { + block_size - (blk.num_tokens + 1) + } else { + block_size - 1 + } + } + Some(blk) => block_size.saturating_sub(blk.num_tokens), + }; + remaining -= remaining.min(tail_free); + needed + remaining.div_ceil(block_size) + } + + /// The sole authority for how many NEW physical blocks the scheduler must + /// find free before it admits `seq_id` with a `prompt_len`-token prompt. + /// Read-only; uses this pool's block size, never a literal. + /// + /// - No table: a fresh `allocate_sequence`, `ceil(prompt_len / block_size)`. + /// - Table whose K/V is not computed (`!is_prefill_ready`): the scheduler + /// drops that table and allocates again, so the need is a fresh + /// allocation minus the blocks the drop gives back (those only this + /// table references). + /// - Computed table (a fork child or a resumed sequence): its blocks, + /// shared or not, are already held, so only the tokens beyond the table + /// plus the first decode token count. That first append is where a + /// shared partial tail is copy-on-written, so a fork child of a + /// mid-block prefix needs exactly one new block. + pub fn incremental_blocks_needed(&self, seq_id: u64, prompt_len: usize) -> usize { + let fresh = prompt_len.div_ceil(self.block_size); + match self.sequence_tables.get(&seq_id) { + None => fresh, + Some(table) if !table.is_prefill_ready() => { + let returned = table + .block_ids + .iter() + .filter(|&&b| self.blocks.get(b).is_some_and(|blk| blk.ref_count == 1)) + .count(); + fresh.saturating_sub(returned) + } + Some(table) => self.blocks_needed_for_appends( + seq_id, + prompt_len.saturating_sub(table.total_tokens) + 1, + ), + } + } + pub fn total_tokens(&self, seq_id: u64) -> Option<usize> { self.sequence_tables.get(&seq_id).map(|t| t.total_tokens) } diff --git a/crates/aien-kv-cache/tests/incremental_blocks_tests.rs b/crates/aien-kv-cache/tests/incremental_blocks_tests.rs new file mode 100644 index 00000000..527dc2ad --- /dev/null +++ b/crates/aien-kv-cache/tests/incremental_blocks_tests.rs @@ -0,0 +1,97 @@ +//! GB10-2: `incremental_blocks_needed` is the one authority for new blocks. +//! Every prediction is checked against what the real append path allocates. + +use aien_kv_cache::AienKvManager; + +const BS: usize = 16; + +fn prefilled(mgr: &mut AienKvManager, id: u64, tokens: usize) { + let prompt: Vec<u32> = (0..tokens as u32).collect(); + mgr.allocate_sequence(id, &prompt).unwrap(); + mgr.mark_prefill_pending(id).unwrap(); + mgr.complete_prefill(id).unwrap(); +} + +/// Appends `n` tokens and returns how many free blocks that consumed. +fn consumed_by_appends(mgr: &mut AienKvManager, id: u64, n: usize) -> usize { + let before = mgr.available_blocks(); + for _ in 0..n { + mgr.append_token(id).unwrap(); + } + before - mgr.available_blocks() +} + +#[test] +fn no_table_needs_a_fresh_allocation_at_the_pool_block_size() { + let mgr = AienKvManager::new(64, 32); + assert_eq!(mgr.incremental_blocks_needed(1, 40), 2); + assert_eq!(mgr.incremental_blocks_needed(1, 64), 2); + assert_eq!(mgr.incremental_blocks_needed(1, 65), 3); + assert_eq!(mgr.incremental_blocks_needed(1, 0), 0); +} + +#[test] +fn fork_child_of_a_partial_prefix_needs_one_copy_on_write_block() { + let mut mgr = AienKvManager::new(64, BS); + prefilled(&mut mgr, 1, 40); // 3 blocks, last holds 8 tokens + mgr.fork_prefilled(1, 2).unwrap(); + assert_eq!(mgr.incremental_blocks_needed(2, 40), 1); + assert_eq!( + consumed_by_appends(&mut mgr, 2, 1), + 1, + "prediction == reality" + ); +} + +#[test] +fn fork_child_of_a_full_prefix_needs_one_fresh_block() { + let mut mgr = AienKvManager::new(64, BS); + prefilled(&mut mgr, 1, 48); // exactly 3 full blocks + mgr.fork_prefilled(1, 2).unwrap(); + assert_eq!(mgr.incremental_blocks_needed(2, 48), 1); + assert_eq!(consumed_by_appends(&mut mgr, 2, 1), 1); +} + +#[test] +fn private_partial_tail_absorbs_the_first_token() { + let mut mgr = AienKvManager::new(64, BS); + prefilled(&mut mgr, 1, 40); // private tail with 8 of 16 slots used + assert_eq!(mgr.incremental_blocks_needed(1, 40), 0); + assert_eq!(consumed_by_appends(&mut mgr, 1, 1), 0); +} + +#[test] +fn prediction_matches_real_appends_across_shapes() { + for prompt in [1usize, 15, 16, 17, 40, 47, 48, 100] { + for appends in [1usize, 2, 8, 9, 16, 17, 40] { + for fork in [false, true] { + let mut mgr = AienKvManager::new(256, BS); + prefilled(&mut mgr, 1, prompt); + let id = if fork { + mgr.fork_prefilled(1, 2).unwrap(); + 2 + } else { + 1 + }; + let predicted = mgr.blocks_needed_for_appends(id, appends); + let actual = consumed_by_appends(&mut mgr, id, appends); + assert_eq!( + predicted, actual, + "prompt {prompt}, appends {appends}, fork {fork}" + ); + } + } + } +} + +#[test] +fn unready_table_counts_a_fresh_allocation_minus_blocks_the_drop_returns() { + let mut mgr = AienKvManager::new(64, BS); + let prompt: Vec<u32> = (0..40).collect(); + mgr.allocate_sequence(1, &prompt).unwrap(); // Allocated, not computed + assert_eq!( + mgr.incremental_blocks_needed(1, 40), + 0, + "own blocks come back" + ); +} diff --git a/crates/aien-runtime/tests/prefill_e2e1.rs b/crates/aien-runtime/tests/prefill_e2e1.rs index fd90fc5c..650f2a3d 100644 --- a/crates/aien-runtime/tests/prefill_e2e1.rs +++ b/crates/aien-runtime/tests/prefill_e2e1.rs @@ -1,4 +1,4 @@ -//! PREFILL-E2E-1: the E2E-0 end-to-end gate at N = 1, 8, 32, 128 and 500 +//! PREFILL-E2E-1: the E2E-0 end-to-end gate at N = 1, 2, 8, 32, 128 and 500 //! branches from ONE shared root prompt (TinyLlama, CPU, strict checkpoint). //! //! `#[ignore]`d for normal CI. Run with `--ignored`; it FAILS (never skips) @@ -28,15 +28,13 @@ //! different branch inputs; (e) backend sequences, KV blocks, arena, worlds and //! scheduler all empty after each N. //! -//! Scheduler admission trap (read, not assumed): crates/aien-scheduler/src/ -//! lib.rs `build_scheduled_batch` step 3 computes `required_blocks = -//! prompt_len.div_ceil(16)` and `break`s when `available_blocks()` is below it, -//! BEFORE it looks at the sequence's existing (shared) block table. So every -//! admitted branch needs a full prompt's worth of FREE blocks at admission -//! even though it shares the root blocks. This test does not change the -//! scheduler: it sizes the pool with that headroom (see `pool_blocks`), -//! records the pool size and the reason, and treats a step-guard hit, an -//! idle-while-waiting step (starved branch) or a scheduler/spine error as FAIL. +//! Scheduler admission (GB10-2): `build_scheduled_batch` step 3 asks +//! `AienKvManager::incremental_blocks_needed` for the NEW blocks a sequence +//! needs, so a fork child that shares the root blocks needs only its +//! copy-on-write block. The pool is sized to the true requirement (prefix + N x +//! private suffix + watermark, see `pool_plan`) and records the pool size and +//! the reason. A step-guard hit, an idle-while-waiting step (starved branch) or +//! a scheduler/spine error is FAIL. //! //! The run stops at the first N that fails (later counts are listed in the //! receipt as `not_run_after_failure`), so a failing gate stays failing and @@ -63,7 +61,10 @@ use async_trait::async_trait; use sha2::{Digest, Sha256}; /// Branch counts of the gate, run in this order. -const BRANCH_COUNTS: [usize; 5] = [1, 8, 32, 128, 500]; +const BRANCH_COUNTS: [usize; 6] = [1, 2, 8, 32, 128, 500]; +/// Branch count from which (d) requires distinct outputs and a mixed decode +/// batch; below it the counts are recorded only (sampling coincidence). +const DIVERGENCE_MIN_N: usize = 8; /// Decode budget per branch. 4 tokens keep N = 500 finishable on CPU: the run /// does N x 4 batched decode rows plus one full control (217-token prefill + 4 /// decodes) per sampled branch, and 4 tokens still cover a partial-block @@ -744,18 +745,14 @@ fn check(name: &'static str, pass: bool, message: String) -> Check { // Pool sizing and branch sampling // --------------------------------------------------------------------------- -/// Scheduler admission hard-codes 16-token blocks (crates/aien-scheduler/src/ -/// lib.rs `required_blocks = prompt_len.div_ceil(16)`); the model config block -/// size must match or the headroom below is wrong. -const SCHEDULER_ADMISSION_BLOCK_TOKENS: usize = 16; -/// Extra free blocks on top of the exact need, so a step never lands on the -/// admission or watermark edge. -const POOL_SLACK_BLOCKS: usize = 16; +/// Extra free blocks on top of the exact need (prefix + N x private suffix + +/// watermark). Zero: the scheduler admits by the KV manager's incremental +/// need (GB10-2), so the pool is sized to the true requirement. +const POOL_SLACK_BLOCKS: usize = 0; struct PoolPlan { prefix_blocks: usize, per_branch_suffix_blocks: usize, - admission_headroom_blocks: usize, watermark_blocks: usize, total_blocks: usize, } @@ -768,25 +765,19 @@ struct PoolPlan { /// copied on the first append (copy-on-write, crates/aien-kv-cache/src/ /// lib.rs `append_token_with_slot`), so the private blocks a branch owns are /// ceil((prompt_len % block_size + appends) / block_size). -/// - admission headroom: the scheduler wants a full prompt's worth of FREE -/// blocks for EVERY branch it admits even though the branch shares the root -/// blocks (the known admission trap), so a pool of exactly prefix + private -/// blocks would starve the last branches. +/// - watermark: the scheduler preempts when free blocks fall below it, so the +/// pool keeps that many free on top. Admission itself needs only the +/// incremental blocks (GB10-2: `AienKvManager::incremental_blocks_needed`), +/// not a whole prompt per branch. fn pool_plan(prompt_len: usize, block_size: usize, n: usize, watermark: usize) -> PoolPlan { let prefix_blocks = prompt_len.div_ceil(block_size); let appends = MAX_TOKENS_PER_BRANCH + 1; let per_branch_suffix_blocks = (prompt_len % block_size + appends).div_ceil(block_size); - let admission_headroom_blocks = prompt_len.div_ceil(SCHEDULER_ADMISSION_BLOCK_TOKENS); PoolPlan { prefix_blocks, per_branch_suffix_blocks, - admission_headroom_blocks, watermark_blocks: watermark, - total_blocks: prefix_blocks - + n * per_branch_suffix_blocks - + admission_headroom_blocks - + watermark - + POOL_SLACK_BLOCKS, + total_blocks: prefix_blocks + n * per_branch_suffix_blocks + watermark + POOL_SLACK_BLOCKS, } } @@ -838,11 +829,6 @@ async fn run_one(n: usize, sh: &Shared<'_>) -> RunResult { std::env::set_var("AIEN_RUNTIME_STATE_DIR", state_dir.path()); let block_size = sh.weights.config.block_size; - assert_eq!( - block_size, SCHEDULER_ADMISSION_BLOCK_TOKENS, - "POOL_SIZING: model block size {block_size} differs from the 16 the scheduler admission \ - hard-codes; the headroom reasoning no longer holds" - ); let watermark = 2usize; let plan = pool_plan(prompt_len, block_size, n, watermark); let max_batch = 32usize.max(n + 2); @@ -1226,8 +1212,14 @@ async fn run_one(n: usize, sh: &Shared<'_>) -> RunResult { // (d) divergence and isolation (isolation proper is the controls above). let distinct: std::collections::HashSet<&Vec<u32>> = generated.iter().collect(); let all_generated = generated.iter().all(|g| !g.is_empty()); - let diverged = all_generated && (n == 1 || distinct.len() >= 2); - let mixed_batch = n == 1 + // Branches diverge only by their sampling seeds, so with few branches and + // 4 tokens each, identical outputs are an ordinary coincidence (observed at + // N=2, 2026-10-03). Divergence is required from DIVERGENCE_MIN_N branches + // on, where every branch sampling the same 4 tokens would be a defect; + // below that the distinct count is recorded, not judged. + let divergence_required = n >= DIVERGENCE_MIN_N; + let diverged = all_generated && (!divergence_required || distinct.len() >= 2); + let mixed_batch = !divergence_required || tap.decode_batches.iter().any(|rows| { let fed: Vec<u32> = rows .iter() @@ -1241,7 +1233,7 @@ async fn run_one(n: usize, sh: &Shared<'_>) -> RunResult { diverged && mixed_batch && parity_pass, format!( "(d) BRANCH_ISOLATION_VIOLATION: N={n}: every branch produced tokens {all_generated}, \ - {} distinct outputs among {n} (need >= 2 when N > 1), a decode batch mixed different \ + {} distinct outputs among {n} (need >= 2 when N >= {DIVERGENCE_MIN_N}), a decode batch mixed different \ branch inputs {mixed_batch}, control parity {parity_pass}{run_note}", distinct.len() ), @@ -1323,12 +1315,11 @@ async fn run_one(n: usize, sh: &Shared<'_>) -> RunResult { "pool_bytes": pool_bytes, "prefix_blocks": plan.prefix_blocks, "per_branch_suffix_blocks": plan.per_branch_suffix_blocks, - "admission_headroom_blocks": plan.admission_headroom_blocks, "watermark_blocks": plan.watermark_blocks, "slack_blocks": POOL_SLACK_BLOCKS, "max_batch_size": max_batch, "host_mem_total_bytes": mem_total_bytes(), - "headroom_reason": "scheduler admission (crates/aien-scheduler/src/lib.rs build_scheduled_batch step 3) requires available_blocks >= prompt_len.div_ceil(16) for every admitted branch before it inspects the shared block table; the pool therefore holds prefix + N x private suffix blocks + one full prompt of free blocks + watermark + slack. Scheduler NOT changed.", + "headroom_reason": "scheduler admission (crates/aien-scheduler/src/lib.rs build_scheduled_batch step 3) asks AienKvManager::incremental_blocks_needed (GB10-2), so a fork child needs only its copy-on-write block at admission; the pool holds prefix + N x private suffix blocks + watermark, no whole-prompt headroom and no slack.", }, "parity": { "result": parity_result, diff --git a/crates/aien-scheduler/src/lib.rs b/crates/aien-scheduler/src/lib.rs index 39bc0e4d..37830b5c 100644 --- a/crates/aien-scheduler/src/lib.rs +++ b/crates/aien-scheduler/src/lib.rs @@ -6,6 +6,7 @@ pub use sequence::*; use aien_abi_core::{ AienInferenceBackend, DecodeOutput, FinishReason, ScheduledBatch, SequenceRequest, StepMetrics, }; +use aien_inference_abi::KV_POOL_EXHAUSTED_PREFIX; use aien_kv_cache::{AienKvManager, PrefillGateError}; use aien_platform::{InferenceWork, Priority}; use parking_lot::RwLock; @@ -348,6 +349,9 @@ impl AienScheduler { let mut current_tokens = 0; let mut prefill_budget = self.config.max_prefill_tokens; let mut preempted_this_step = false; + // New blocks promised to sequences admitted into decode this step + // (copy-on-write on their first token) but not allocated until the backend runs. + let mut reserved_blocks = 0usize; // 1. Watermark Memory Pressure Check: Preempt lowest priority sequence if below watermark { @@ -494,17 +498,49 @@ impl AienScheduler { } }; - let required_blocks = prompt_len.div_ceil(16); - let available = self.kv_manager.read().available_blocks(); + // The KV manager is the only authority on how many NEW physical + // blocks this sequence needs (its own pool block size, blocks it + // already owns or shares, a pending copy-on-write). The need is + // read BEFORE the sequence leaves its queue. + let (needed_blocks, free_blocks, pool_blocks) = { + let kv = self.kv_manager.read(); + ( + kv.incremental_blocks_needed(next_seq_id.to_u64(), prompt_len), + kv.available_blocks(), + kv.total_block_count(), + ) + }; + // Blocks promised to sequences admitted earlier in this step + // that have not allocated them yet (forks entering decode). + let available = free_blocks.saturating_sub(reserved_blocks); // Preempted sequences require headroom above watermark to prevent thrashing - let min_needed = if is_preempted { - required_blocks + self.config.watermark_blocks + let watermark_headroom = if is_preempted { + self.config.watermark_blocks } else { - required_blocks + 0 }; + let min_needed = needed_blocks + watermark_headroom; 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 + // nothing running and nothing scheduled, would wait forever. + let nothing_can_free = self.running_sequences.is_empty() + && decode_requests.is_empty() + && prefill_requests.is_empty(); + if min_needed > pool_blocks || nothing_can_free { + return Err(format!( + "{KV_POOL_EXHAUSTED_PREFIX} admission of sequence {} needs {} new KV \ + blocks (plus {} watermark) but only {} are free ({} in the pool) and \ + nothing is running that could free more; the request stays queued", + next_seq_id.to_u64(), + needed_blocks, + watermark_headroom, + available, + pool_blocks, + )); + } break; } @@ -544,6 +580,7 @@ impl AienScheduler { seq.prompt_tokens_prefilled = prompt_len; decode_requests.push(next_seq_id.to_u64()); current_tokens += 1; + reserved_blocks += needed_blocks; self.running_sequences.push(next_seq_id); continue; } diff --git a/crates/aien-scheduler/tests/kv_incremental_admission_test.rs b/crates/aien-scheduler/tests/kv_incremental_admission_test.rs new file mode 100644 index 00000000..98a8cf84 --- /dev/null +++ b/crates/aien-scheduler/tests/kv_incremental_admission_test.rs @@ -0,0 +1,176 @@ +//! GB10-2: the KV manager is the sole authority for how many NEW physical +//! blocks a sequence needs, and the scheduler admits by that number. +//! +//! On main (c75c583) `build_scheduled_batch` step 3 computes +//! `required_blocks = prompt_len.div_ceil(16)` (a literal 16, not the pool's +//! block size) and breaks when the free pool is below it, BEFORE it looks at +//! the sequence's block table. A fork child that already shares its parent's +//! prefix blocks is therefore refused unless the pool could hold the WHOLE +//! prompt again, and a pool with a block size other than 16 is mis-counted. +//! These tests use only APIs that exist on main, so they run (and FAIL) there. + +use aien_inference_abi::{SamplingParams, SequenceRequest, KV_POOL_EXHAUSTED_PREFIX}; +use aien_kv_cache::create_shared_kv_manager; +use aien_scheduler::{AienScheduler, SchedulerConfig, SequenceId}; + +fn config() -> SchedulerConfig { + SchedulerConfig { + max_batch_size: 16, + max_batch_tokens: 4096, + max_prefill_tokens: 4096, + prefill_chunk_size: 4096, + chunk_prefill: true, + watermark_blocks: 1, + } +} + +fn request(id: u64, prompt: &[u32]) -> SequenceRequest { + SequenceRequest { + request_id: id, + prompt_tokens: prompt.to_vec(), + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 4, + stop_token_ids: vec![], + }, + arrival_time_ns: 0, + priority: 1, + } +} + +/// Parent with a computed 40-token prefix (3 blocks of 16, last one partial), +/// forked to a child that shares all three blocks. +fn parent_and_forked_child( + total_blocks: usize, + block_size: usize, +) -> (aien_kv_cache::SharedKvManager, AienScheduler, u64, Vec<u32>) { + let kv = create_shared_kv_manager(total_blocks, block_size); + let scheduler = AienScheduler::new(config(), kv.clone()); + let parent = SequenceId::new(2, 1).unwrap().to_u64(); + let child = SequenceId::new(3, 1).unwrap().to_u64(); + let prompt: Vec<u32> = (10..50).collect(); + { + let mut w = kv.write(); + w.allocate_sequence(parent, &prompt).expect("allocate"); + w.mark_prefill_pending(parent).expect("pending"); + w.complete_prefill(parent).expect("fence"); + w.fork_prefilled(parent, child).expect("fork"); + } + (kv, scheduler, child, prompt) +} + +#[test] +fn fork_child_is_admitted_on_incremental_blocks_only() { + // 5-block pool. Parent holds 3, child shares them: 2 blocks are free. + // The child's full prompt is 3 blocks (> 2 free) but it only needs ONE new + // block (copy-on-write of the shared partial tail on its first decode). + let (kv, mut scheduler, child, prompt) = parent_and_forked_child(5, 16); + assert_eq!(kv.read().available_blocks(), 2, "setup: 2 free blocks"); + scheduler.submit_request(request(child, &prompt)); + + let batch = scheduler.build_scheduled_batch().expect("schedule"); + let admitted = batch + .as_ref() + .is_some_and(|b| b.decode_requests.contains(&child)); + assert!( + admitted, + "KV_ADMISSION_TRAP: forked child {child} shares its parent's 3 prefix blocks and needs \ + 1 new block, the pool has 2 free, but admission demanded a whole prompt's blocks (3); \ + batch = {batch:?}" + ); +} + +#[test] +fn admission_uses_the_pool_block_size_not_a_literal_16() { + // Block size 32: a 40-token prompt needs 2 blocks and the pool has 2. + // Main counts 40.div_ceil(16) = 3 and refuses it. + let kv = create_shared_kv_manager(2, 32); + let mut scheduler = AienScheduler::new(config(), kv.clone()); + let prompt: Vec<u32> = (10..50).collect(); + let id = SequenceId::new(4, 1).unwrap().to_u64(); + scheduler.submit_request(request(id, &prompt)); + + let batch = scheduler.build_scheduled_batch().expect("schedule"); + let admitted = batch + .as_ref() + .is_some_and(|b| b.prefill_requests.iter().any(|r| r.request_id == id)); + assert!( + admitted, + "KV_ADMISSION_BLOCK_SIZE: 40 tokens at block size 32 need 2 blocks and 2 are free, but \ + admission used a hard-coded 16 (3 blocks); batch = {batch:?}" + ); +} + +#[test] +fn exhausted_pool_with_nothing_running_fails_loud() { + // Negative control. 3-block pool, all held by the parent, child shares them. + // The child needs 1 new block (copy-on-write), 0 are free, nothing is running + // that could ever free one: the scheduler must say so, not wait forever. + let (kv, mut scheduler, child, prompt) = parent_and_forked_child(3, 16); + assert_eq!(kv.read().available_blocks(), 0, "setup: pool is full"); + scheduler.submit_request(request(child, &prompt)); + + let result = scheduler.build_scheduled_batch(); + let err = result.expect_err( + "KV_ADMISSION_SILENT_WAIT: pool cannot admit the child and nothing is running, yet \ + build_scheduled_batch returned Ok", + ); + assert!( + err.starts_with(KV_POOL_EXHAUSTED_PREFIX), + "error must start with the shared marker, got: {err}" + ); + assert!( + err.contains(&format!("sequence {child}")), + "error must name the sequence, got: {err}" + ); + assert!( + err.contains("needs 1 new KV blocks") && err.contains("only 0 are free"), + "error must say needed vs available, got: {err}" + ); +} + +#[test] +fn shortfall_while_others_run_waits_without_error() { + // Control (must pass before and after): when a running sequence may still + // free blocks, a shortfall is ordinary queueing, not an error. + let kv = create_shared_kv_manager(3, 16); + let mut scheduler = AienScheduler::new(config(), kv.clone()); + let first: Vec<u32> = (10..58).collect(); // 48 tokens = 3 blocks + let second: Vec<u32> = (10..26).collect(); // 16 tokens = 1 block + let a = SequenceId::new(5, 1).unwrap().to_u64(); + let b = SequenceId::new(6, 1).unwrap().to_u64(); + scheduler.submit_request(request(a, &first)); + scheduler.submit_request(request(b, &second)); + + let batch = scheduler + .build_scheduled_batch() + .expect("a shortfall with a running sequence must not be an error") + .expect("first sequence is admitted"); + assert!(batch.prefill_requests.iter().any(|r| r.request_id == a)); + assert!(!batch.prefill_requests.iter().any(|r| r.request_id == b)); + assert_eq!(scheduler.waiting_count(), 1, "second request keeps waiting"); +} + +#[test] +fn same_step_fork_admissions_reserve_their_copy_on_write_blocks() { + // 4-block pool: parent holds 3, ONE block free. Two children each need one + // new block on their first token. Admitting both in one step would promise + // the same free block twice; only the first may enter this batch. + let (kv, mut scheduler, first_child, prompt) = parent_and_forked_child(4, 16); + let second_child = SequenceId::new(7, 1).unwrap().to_u64(); + let parent = SequenceId::new(2, 1).unwrap().to_u64(); + kv.write() + .fork_prefilled(parent, second_child) + .expect("fork"); + assert_eq!(kv.read().available_blocks(), 1, "setup: 1 free block"); + scheduler.submit_request(request(first_child, &prompt)); + scheduler.submit_request(request(second_child, &prompt)); + + let batch = scheduler + .build_scheduled_batch() + .expect("second child waits, it is not an error: the first is scheduled") + .expect("first child admitted"); + assert_eq!(batch.decode_requests, vec![first_child]); + assert_eq!(scheduler.waiting_count(), 1, "second child keeps waiting"); +}