From a19712a50e07e46805f48642b57eb9986cb13146 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 13:21:52 -0500 Subject: [PATCH] aien-dual-observation: read-only serve observation snapshot and deltas (DUAL-3a) ARCH-0031: a new crate that builds an immutable ServeObservationSnapshot from existing exact counters only (SchedulerMetrics, queue and arena counts, SchedulerConfig limits, AienKvManager block counts and KvMetrics, the caller's last StepMetrics and ScheduledBatch), with every field documenting its source counter, every quotient a Density whose value() is None on a zero denominator, and ObservationDelta::between for exact arrival / completion / preemption differences that refuses reversed or foreign snapshots. No interpolation, no second ledger, no state between calls. Living in its own crate it reaches public counters only and cannot touch a scheduling or KV decision. Tests run the real scheduler and KV manager with the mock backend and hold the ledgers closed at every snapshot: physical + free == total, shared + private == physical, arena == running + waiting + preempted, admitted == finished + held. Receipt: docs/campaigns/dual/2026-10-04-macro-snapshot-receipt.md. No gate is claimed. Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- .crumb | 10 +- Cargo.lock | 13 + Cargo.toml | 1 + crates/aien-dual-observation/Cargo.toml | 18 + crates/aien-dual-observation/src/lib.rs | 379 ++++++++++++++++++ .../tests/snapshot_conservation.rs | 332 +++++++++++++++ .../dual/2026-10-04-macro-snapshot-receipt.md | 109 +++++ 7 files changed, 857 insertions(+), 5 deletions(-) create mode 100644 crates/aien-dual-observation/Cargo.toml create mode 100644 crates/aien-dual-observation/src/lib.rs create mode 100644 crates/aien-dual-observation/tests/snapshot_conservation.rs create mode 100644 docs/campaigns/dual/2026-10-04-macro-snapshot-receipt.md diff --git a/.crumb b/.crumb index b4bb4b9b..0503c299 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:dfcfd805db0c30c667bc5682364bd3acb3383d494967dcae39f2420739723d7d", - "compiled_at": "2026-10-04T18:57:26Z", + "compiled_at": "2026-10-04T19:07:25Z", "compiler": "crumb-compile/1", - "digest": "sha256:21c2ec6095db6b30d3811be32c3bd148105fb2987dc3b81cfd2c6c0481be16e3", + "digest": "sha256:c96cedd67ca67fa0d0dc9fa9a2eff7f7bdfe480ff8725ba72b1c387e5ef6a5e4", "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", - "files": 671, - "generated_at_commit": "9d66c8f2d30bb7d770cb8e14282175cc7dfec043", - "source_tree": "sha256:baf4a50c75a7c7929708676ca137157178d0cd1898c183037ece666a25494c48" + "files": 675, + "generated_at_commit": "2f9570a04f137de59afda33d29d3994993ab56c9", + "source_tree": "sha256:f958c571fffbecd3c2b0bea616aedad59a58c39063d50017eec51b80c4e02ca0" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 875116cd..3ef9ad1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -84,6 +84,19 @@ dependencies = [ "serde_json", ] +[[package]] +name = "aien-dual-observation" +version = "0.1.0" +dependencies = [ + "aien-abi-core", + "aien-inference-abi", + "aien-kv-cache", + "aien-scheduler", + "serde", + "serde_json", + "tokio", +] + [[package]] name = "aien-evaluation-protocol" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index ebd69f87..e30cecc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ members = [ "crates/crumbs", "crates/aien-closure", "crates/aien-switchboard", + "crates/aien-dual-observation", "tools/aien-test", ] diff --git a/crates/aien-dual-observation/Cargo.toml b/crates/aien-dual-observation/Cargo.toml new file mode 100644 index 00000000..0364847d --- /dev/null +++ b/crates/aien-dual-observation/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "aien-dual-observation" +version = "0.1.0" +edition = "2021" +authors = ["Drake Stapleton "] +description = "DUAL observation: read-only macroscopic snapshot of the serve path built from existing exact counters (ARCH-0031 DUAL-3a)" +license.workspace = true + +[dependencies] +aien-abi-core = { path = "../aien-abi-core" } +aien-kv-cache = { path = "../aien-kv-cache" } +aien-scheduler = { path = "../aien-scheduler" } +serde = { version = "1.0", features = ["derive"] } + +[dev-dependencies] +aien-inference-abi = { path = "../aien-inference-abi" } +serde_json = "1.0" +tokio = { version = "1.37", features = ["full"] } diff --git a/crates/aien-dual-observation/src/lib.rs b/crates/aien-dual-observation/src/lib.rs new file mode 100644 index 00000000..f83ce163 --- /dev/null +++ b/crates/aien-dual-observation/src/lib.rs @@ -0,0 +1,379 @@ +//! DUAL observation: a read-only macroscopic snapshot of the serve path +//! (ARCH-0031 DUAL-3a instrumentation). +//! +//! [`ServeObservationSnapshot::capture`] copies existing exact counters from +//! the scheduler, the KV manager and (when the caller has them) the last +//! `StepMetrics` and `ScheduledBatch` into one immutable struct, and derives +//! normalized densities from them. [`ObservationDelta::between`] subtracts two +//! snapshots to give arrival, completion and preemption counts over the +//! interval. +//! +//! Rules this crate keeps: +//! +//! - Every field documents the counter it is copied from. There is no second +//! ledger: nothing here is incremented, remembered between calls or +//! estimated. A snapshot is a pure function of the counters at the instant +//! `capture` ran. +//! - Every quotient is a [`Density`] with its exact numerator and denominator; +//! `Density::value` is `None` when the denominator is zero. No field is +//! interpolated or guessed. +//! - This crate reads through `&AienScheduler` and `&AienKvManager` only. It +//! cannot change a scheduling, admission, preemption or KV decision, and no +//! field of a snapshot is an authority input anywhere (ADR 0031 §6). +//! +//! The scheduler's internal step counter is private; the generation here is +//! `SchedulerMetrics::total_steps`, which counts completed steps that executed +//! a batch. Two snapshots with equal `generation` were taken without a step +//! completing between them. + +use aien_abi_core::{ScheduledBatch, StepMetrics}; +use aien_kv_cache::{AienKvManager, KvMetrics}; +use aien_scheduler::AienScheduler; +use serde::{Deserialize, Serialize}; + +/// An exact ratio kept as its two integers. `value()` is the normalized +/// density `numerator / denominator`, or `None` when the denominator is zero +/// (the zero-denominator rule for every density in this crate). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Density { + pub numerator: usize, + pub denominator: usize, +} + +impl Density { + pub fn new(numerator: usize, denominator: usize) -> Self { + Self { + numerator, + denominator, + } + } + + /// `numerator / denominator`, `None` when `denominator == 0`. + pub fn value(&self) -> Option { + if self.denominator == 0 { + None + } else { + Some(self.numerator as f64 / self.denominator as f64) + } + } +} + +/// Copy of the last `StepMetrics` the caller received from +/// `AienScheduler::step`. `step_latency_us` is left out on purpose: it is a +/// timing, not a count, and DUAL observation records counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct StepReading { + /// `StepMetrics::prefill_tokens_processed`. + pub prefill_tokens_processed: usize, + /// `StepMetrics::decode_tokens_emitted`. + pub decode_tokens_emitted: usize, + /// `StepMetrics::active_kv_blocks` (`AienKvManager::allocated_block_count` + /// after the step, as the scheduler fills it). + pub active_kv_blocks: usize, +} + +impl From<&StepMetrics> for StepReading { + fn from(m: &StepMetrics) -> Self { + Self { + prefill_tokens_processed: m.prefill_tokens_processed, + decode_tokens_emitted: m.decode_tokens_emitted, + active_kv_blocks: m.active_kv_blocks, + } + } +} + +/// Sizes of the last `ScheduledBatch` the caller saw. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct BatchReading { + /// `ScheduledBatch::step_id`. + pub step_id: u64, + /// `ScheduledBatch::prefill_requests.len()`. + pub prefill_requests: usize, + /// `ScheduledBatch::decode_requests.len()`. + pub decode_requests: usize, + /// Sum of `prompt_tokens.len()` over `prefill_requests` plus one per + /// decode request: the quantity the scheduler compares against + /// `max_batch_tokens`. + pub batch_tokens: usize, +} + +impl From<&ScheduledBatch> for BatchReading { + fn from(b: &ScheduledBatch) -> Self { + Self { + step_id: b.step_id, + prefill_requests: b.prefill_requests.len(), + decode_requests: b.decode_requests.len(), + batch_tokens: b + .prefill_requests + .iter() + .map(|r| r.prompt_tokens.len()) + .sum::() + + b.decode_requests.len(), + } + } +} + +/// One read-only macroscopic snapshot of the serve path. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServeObservationSnapshot { + /// `SchedulerMetrics::total_steps`: completed steps that executed a batch. + pub generation: u64, + + // Scheduler queues and arena. + /// `AienScheduler::waiting_count()`. + pub waiting: usize, + /// `AienScheduler::preempted_count()`. + pub preempted: usize, + /// `AienScheduler::running_count()`. + pub running: usize, + /// `SequenceArena::active_count()` via `AienScheduler::arena()`. + pub arena_active: usize, + + // Scheduler lifetime counters (`SchedulerMetrics`). + /// `SchedulerMetrics::admitted_requests` (counts `submit_request` and + /// `submit_work`; a `fork_sequence` child is not counted here). + pub admitted_requests: u64, + /// `SchedulerMetrics::finished_requests`. + pub finished_requests: u64, + /// `SchedulerMetrics::preempted_requests` (lifetime count of preemption + /// events, not the current queue length). + pub preempted_requests: u64, + /// `SchedulerMetrics::total_prefill_tokens`. + pub total_prefill_tokens: u64, + /// `SchedulerMetrics::total_decode_tokens`. + pub total_decode_tokens: u64, + /// `SchedulerMetrics::chunked_prefill_steps`. + pub chunked_prefill_steps: u64, + + // Scheduler limits (`SchedulerConfig`). + /// `SchedulerConfig::max_batch_size`. + pub max_batch_size: usize, + /// `SchedulerConfig::max_batch_tokens`. + pub max_batch_tokens: usize, + /// `SchedulerConfig::watermark_blocks`. + pub watermark_blocks: usize, + + // KV pool (`AienKvManager`). + /// `AienKvManager::total_block_count()`. + pub kv_total_blocks: usize, + /// `AienKvManager::available_blocks()` (free-list length). + pub kv_free_blocks: usize, + /// `AienKvManager::allocated_block_count()` (`total - free`). + pub kv_allocated_blocks: usize, + /// `AienKvManager::active_sequence_count()` (block tables held). + pub kv_active_tables: usize, + /// `KvMetrics::physical_pages` (blocks with `ref_count > 0`). + pub kv_physical_pages: usize, + /// `KvMetrics::logical_pages` (sum of table lengths). + pub kv_logical_pages: usize, + /// `KvMetrics::shared_pages` (blocks with `ref_count > 1`). + pub kv_shared_pages: usize, + /// `KvMetrics::private_pages` (blocks with `ref_count == 1`). + pub kv_private_pages: usize, + /// `KvMetrics::cow_faults`. + pub kv_cow_faults: usize, + /// `KvMetrics::used_blocks` (equals `physical_pages` by its definition). + pub kv_used_blocks: usize, + /// `AienKvManager::available_blocks() < SchedulerConfig::watermark_blocks`, + /// the pool half of the scheduler's preemption predicate (the other half, + /// "something is running", is `running > 0`). + pub kv_below_watermark: bool, + + // Last step and batch, when the caller had them. + pub last_step: Option, + pub last_batch: Option, + + // Normalized densities (used / capacity). Denominator zero gives None. + /// `kv_allocated_blocks / kv_total_blocks`. + pub kv_block_density: Density, + /// `(kv_logical_pages - kv_physical_pages) / kv_logical_pages`: the share + /// of logical pages served by sharing. `None` when no table holds a page. + pub kv_sharing_density: Density, + /// `running / max_batch_size`. + pub running_slot_density: Density, + /// `(prefill_requests + decode_requests) / max_batch_size` of the last + /// batch; numerator 0 when no batch was given. + pub batch_slot_density: Density, + /// `batch_tokens / max_batch_tokens` of the last batch; numerator 0 when + /// no batch was given. + pub batch_token_density: Density, +} + +impl ServeObservationSnapshot { + /// Copies the counters. `kv` must be the manager the scheduler was built + /// with; the caller holds the read guard so both reads see one instant. + pub fn capture( + scheduler: &AienScheduler, + kv: &AienKvManager, + last_step: Option<&StepMetrics>, + last_batch: Option<&ScheduledBatch>, + ) -> Self { + let m = scheduler.metrics(); + let cfg = scheduler.config(); + let km: KvMetrics = kv.metrics(); + + let kv_total_blocks = kv.total_block_count(); + let kv_free_blocks = kv.available_blocks(); + let kv_allocated_blocks = kv.allocated_block_count(); + let running = scheduler.running_count(); + let last_step = last_step.map(StepReading::from); + let last_batch = last_batch.map(BatchReading::from); + let (batch_slots, batch_tokens) = match &last_batch { + Some(b) => (b.prefill_requests + b.decode_requests, b.batch_tokens), + None => (0, 0), + }; + + Self { + generation: m.total_steps, + waiting: scheduler.waiting_count(), + preempted: scheduler.preempted_count(), + running, + arena_active: scheduler.arena().active_count(), + 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, + max_batch_size: cfg.max_batch_size, + max_batch_tokens: cfg.max_batch_tokens, + watermark_blocks: cfg.watermark_blocks, + kv_total_blocks, + kv_free_blocks, + kv_allocated_blocks, + kv_active_tables: kv.active_sequence_count(), + kv_physical_pages: km.physical_pages, + kv_logical_pages: km.logical_pages, + kv_shared_pages: km.shared_pages, + kv_private_pages: km.private_pages, + kv_cow_faults: km.cow_faults, + kv_used_blocks: km.used_blocks, + kv_below_watermark: kv_free_blocks < cfg.watermark_blocks, + last_step, + last_batch, + kv_block_density: Density::new(kv_allocated_blocks, kv_total_blocks), + kv_sharing_density: Density::new( + km.logical_pages.saturating_sub(km.physical_pages), + km.logical_pages, + ), + running_slot_density: Density::new(running, cfg.max_batch_size), + batch_slot_density: Density::new(batch_slots, cfg.max_batch_size), + batch_token_density: Density::new(batch_tokens, cfg.max_batch_tokens), + } + } +} + +/// Why two snapshots could not be subtracted. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum DeltaError { + /// `later.generation < earlier.generation`: the order is reversed or the + /// snapshots come from different schedulers. + GenerationWentBackwards { earlier: u64, later: u64 }, + /// A lifetime counter decreased, which the scheduler never does; the + /// snapshots are not from one scheduler. + CounterWentBackwards { + counter: &'static str, + earlier: u64, + later: u64, + }, + /// The pool size differs; the snapshots are not from one KV manager. + PoolSizeChanged { earlier: usize, later: usize }, +} + +/// Exact differences between two snapshots of the same scheduler. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObservationDelta { + /// `later.generation - earlier.generation`: completed steps in between. + pub steps: u64, + /// `admitted_requests` difference: requests that arrived (were submitted). + pub arrivals: u64, + /// `finished_requests` difference. + pub completions: u64, + /// `preempted_requests` difference: preemption events. + pub preemptions: u64, + /// `total_prefill_tokens` difference. + pub prefill_tokens: u64, + /// `total_decode_tokens` difference. + pub decode_tokens: u64, + /// `later.kv_allocated_blocks - earlier.kv_allocated_blocks`, signed. + pub kv_allocated_change: i64, + /// `later.running - earlier.running`, signed. + pub running_change: i64, + /// `later.waiting - earlier.waiting`, signed. + pub waiting_change: i64, +} + +impl ObservationDelta { + /// `later - earlier`. Refuses reversed order and snapshots that cannot + /// come from one scheduler and one pool. + pub fn between( + earlier: &ServeObservationSnapshot, + later: &ServeObservationSnapshot, + ) -> Result { + if later.generation < earlier.generation { + return Err(DeltaError::GenerationWentBackwards { + earlier: earlier.generation, + later: later.generation, + }); + } + if later.kv_total_blocks != earlier.kv_total_blocks { + return Err(DeltaError::PoolSizeChanged { + earlier: earlier.kv_total_blocks, + later: later.kv_total_blocks, + }); + } + let diff = |counter: &'static str, a: u64, b: u64| -> Result { + b.checked_sub(a).ok_or(DeltaError::CounterWentBackwards { + counter, + earlier: a, + later: b, + }) + }; + Ok(Self { + steps: later.generation - earlier.generation, + arrivals: diff( + "admitted_requests", + earlier.admitted_requests, + later.admitted_requests, + )?, + completions: diff( + "finished_requests", + earlier.finished_requests, + later.finished_requests, + )?, + preemptions: diff( + "preempted_requests", + earlier.preempted_requests, + later.preempted_requests, + )?, + prefill_tokens: diff( + "total_prefill_tokens", + earlier.total_prefill_tokens, + later.total_prefill_tokens, + )?, + decode_tokens: diff( + "total_decode_tokens", + earlier.total_decode_tokens, + later.total_decode_tokens, + )?, + kv_allocated_change: later.kv_allocated_blocks as i64 + - earlier.kv_allocated_blocks as i64, + running_change: later.running as i64 - earlier.running as i64, + waiting_change: later.waiting as i64 - earlier.waiting as i64, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn density_zero_denominator_is_none() { + assert_eq!(Density::new(0, 0).value(), None); + assert_eq!(Density::new(5, 0).value(), None); + assert_eq!(Density::new(0, 4).value(), Some(0.0)); + assert_eq!(Density::new(2, 4).value(), Some(0.5)); + assert_eq!(Density::new(4, 4).value(), Some(1.0)); + } +} diff --git a/crates/aien-dual-observation/tests/snapshot_conservation.rs b/crates/aien-dual-observation/tests/snapshot_conservation.rs new file mode 100644 index 00000000..9ae85562 --- /dev/null +++ b/crates/aien-dual-observation/tests/snapshot_conservation.rs @@ -0,0 +1,332 @@ +//! Conservation and zero-denominator tests for the DUAL serve observation +//! snapshot, over the real scheduler and KV manager with the mock backend. +//! +//! Every assertion compares two existing ledgers of the production state +//! machine against each other; nothing here is a model of what they should +//! be. The workload submits requests only through `submit_request` and never +//! cancels, so the sequence ledgers close exactly (see `lib.rs` field docs +//! for the two cases, fork children and cancellation, where +//! `admitted_requests` is not the right denominator). + +use aien_abi_core::{SamplingParams, ScheduledBatch, SequenceRequest, StepMetrics}; +use aien_dual_observation::{DeltaError, ObservationDelta, ServeObservationSnapshot}; +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_scheduler::{AienScheduler, SchedulerConfig}; + +fn request(id: u64, prompt_len: usize, priority: u8, max_tokens: usize) -> SequenceRequest { + SequenceRequest { + request_id: id, + prompt_tokens: (0..prompt_len as u32).collect(), + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens, + stop_token_ids: vec![], + }, + arrival_time_ns: 0, + priority, + } +} + +fn config(max_batch_size: usize, watermark_blocks: usize) -> SchedulerConfig { + SchedulerConfig { + max_batch_size, + max_batch_tokens: 1024, + max_prefill_tokens: 100, + prefill_chunk_size: 64, + chunk_prefill: true, + watermark_blocks, + } +} + +/// Checks that hold for every snapshot of a scheduler fed only through +/// `submit_request` without cancellation. +fn assert_conserved(s: &ServeObservationSnapshot, where_: &str) { + // KV: the free list and the refcount ledger partition the pool. + assert_eq!( + s.kv_physical_pages + s.kv_free_blocks, + s.kv_total_blocks, + "{where_}: physical (ref_count>0) + free == total" + ); + assert_eq!( + s.kv_allocated_blocks + s.kv_free_blocks, + s.kv_total_blocks, + "{where_}: allocated + free == total" + ); + assert_eq!(s.kv_used_blocks, s.kv_physical_pages, "{where_}"); + assert_eq!( + s.kv_shared_pages + s.kv_private_pages, + s.kv_physical_pages, + "{where_}: shared + private == physical" + ); + assert!(s.kv_logical_pages >= s.kv_physical_pages, "{where_}"); + // Sequences: the arena holds exactly the queued and running records. + assert_eq!( + s.arena_active, + s.running + s.waiting + s.preempted, + "{where_}: arena == running + waiting + preempted" + ); + // Lifetime ledger: every admitted request is finished or still held. + assert_eq!( + s.admitted_requests, + s.finished_requests + (s.running + s.waiting + s.preempted) as u64, + "{where_}: admitted == finished + held" + ); + // Densities are the exact counters. + assert_eq!(s.kv_block_density.numerator, s.kv_allocated_blocks); + assert_eq!(s.kv_block_density.denominator, s.kv_total_blocks); + assert_eq!(s.running_slot_density.numerator, s.running); + assert_eq!(s.running_slot_density.denominator, s.max_batch_size); + assert_eq!( + s.kv_sharing_density.numerator, + s.kv_logical_pages - s.kv_physical_pages + ); + assert_eq!(s.kv_sharing_density.denominator, s.kv_logical_pages); + assert_eq!( + s.kv_below_watermark, + s.kv_free_blocks < s.watermark_blocks, + "{where_}" + ); + if let Some(step) = &s.last_step { + // StepMetrics::active_kv_blocks is allocated_block_count after the + // step, read before the caller captured; a capture right after the + // step sees the same number. + assert_eq!(step.active_kv_blocks, s.kv_allocated_blocks, "{where_}"); + } + if let Some(b) = &s.last_batch { + assert_eq!( + s.batch_slot_density.numerator, + b.prefill_requests + b.decode_requests + ); + assert_eq!(s.batch_token_density.numerator, b.batch_tokens); + assert!(b.prefill_requests + b.decode_requests <= s.max_batch_size); + } +} + +/// Runs a scheduler through a mixed workload (admission, chunked prefill, +/// watermark preemption, completion) and snapshots after every step. +async fn run_and_snapshot( + kv_blocks: usize, + cfg: SchedulerConfig, + requests: Vec, + max_steps: usize, +) -> Vec { + let kv = create_shared_kv_manager(kv_blocks, 16); + let mut scheduler = AienScheduler::new(cfg, kv.clone()); + let mut backend = MockInferenceBackend::new(0); + let mut snaps = Vec::new(); + + snaps.push(ServeObservationSnapshot::capture( + &scheduler, + &kv.read(), + None, + None, + )); + for r in requests { + scheduler.submit_request(r); + snaps.push(ServeObservationSnapshot::capture( + &scheduler, + &kv.read(), + None, + None, + )); + } + let mut steps = 0; + while steps < max_steps + && (scheduler.waiting_count() + scheduler.running_count() + scheduler.preempted_count() > 0) + { + steps += 1; + let result = scheduler.step(&mut backend).await; + let metrics: Option = match result { + Ok(Some((_, m))) => Some(m), + Ok(None) => None, + Err(e) => panic!("step error in conservation workload: {e}"), + }; + snaps.push(ServeObservationSnapshot::capture( + &scheduler, + &kv.read(), + metrics.as_ref(), + None, + )); + } + assert_eq!(scheduler.running_count(), 0, "workload must drain"); + snaps +} + +fn mixed_requests() -> Vec { + vec![ + request(1, 20, 3, 3), + request(2, 150, 1, 2), + request(3, 7, 0, 4), + request(4, 64, 2, 1), + request(5, 33, 1, 2), + ] +} + +#[tokio::test] +async fn ledgers_close_at_every_snapshot_under_plenty() { + let snaps = run_and_snapshot(256, config(8, 2), mixed_requests(), 64).await; + assert!(snaps.len() > 6); + for (i, s) in snaps.iter().enumerate() { + assert_conserved(s, &format!("plenty snapshot {i}")); + } + let last = snaps.last().unwrap(); + assert_eq!(last.kv_allocated_blocks, 0); + assert_eq!(last.arena_active, 0); + assert_eq!(last.finished_requests, 5); + assert_eq!(last.kv_block_density.value(), Some(0.0)); +} + +#[tokio::test] +async fn ledgers_close_at_every_snapshot_under_watermark_pressure() { + // 6-block pool, watermark 3: two 32-token prompts fill 4 blocks, the pool + // drops below the watermark and the lower priority sequence is preempted. + let cfg = SchedulerConfig { + max_batch_size: 4, + max_batch_tokens: 1024, + max_prefill_tokens: 512, + prefill_chunk_size: 128, + chunk_prefill: false, + watermark_blocks: 3, + }; + let reqs = vec![request(1, 32, 3, 4), request(2, 32, 1, 4)]; + let snaps = run_and_snapshot(6, cfg, reqs, 64).await; + for (i, s) in snaps.iter().enumerate() { + assert_conserved(s, &format!("pressure snapshot {i}")); + } + assert!( + snaps.iter().any(|s| s.kv_below_watermark && s.running > 0), + "the workload must cross the watermark while something runs" + ); + let last = snaps.last().unwrap(); + assert!( + last.preempted_requests >= 1, + "a preemption must have happened" + ); + assert_eq!(last.finished_requests, 2); + assert_eq!(last.kv_allocated_blocks, 0); +} + +#[tokio::test] +async fn deltas_are_exact_counter_differences() { + let snaps = run_and_snapshot(256, config(8, 2), mixed_requests(), 64).await; + let first = &snaps[0]; + let after_submits = &snaps[5]; + let last = snaps.last().unwrap(); + + let d = ObservationDelta::between(first, after_submits).unwrap(); + assert_eq!(d.steps, 0); + assert_eq!(d.arrivals, 5); + assert_eq!(d.completions, 0); + assert_eq!(d.waiting_change, 5); + + let d = ObservationDelta::between(after_submits, last).unwrap(); + assert_eq!(d.arrivals, 0); + assert_eq!(d.completions, 5); + assert_eq!(d.steps, last.generation - after_submits.generation); + assert_eq!(d.waiting_change, -5); + assert_eq!(d.kv_allocated_change, 0); + assert_eq!(d.prefill_tokens, last.total_prefill_tokens); + assert_eq!(d.decode_tokens, last.total_decode_tokens); + // Prefill tokens over the run equal the prompt tokens submitted. + assert_eq!(d.prefill_tokens, 20 + 150 + 7 + 64 + 33); + + // Consecutive deltas sum to the whole. + let mut arrivals = 0; + let mut completions = 0; + let mut steps = 0; + for w in snaps.windows(2) { + let d = ObservationDelta::between(&w[0], &w[1]).unwrap(); + arrivals += d.arrivals; + completions += d.completions; + steps += d.steps; + } + assert_eq!(arrivals, 5); + assert_eq!(completions, 5); + assert_eq!(steps, last.generation); +} + +#[tokio::test] +async fn reversed_or_foreign_snapshots_are_refused() { + let snaps = run_and_snapshot(256, config(8, 2), mixed_requests(), 64).await; + let first = &snaps[0]; + let last = snaps.last().unwrap(); + assert!(matches!( + ObservationDelta::between(last, first), + Err(DeltaError::GenerationWentBackwards { .. }) + )); + + let other = run_and_snapshot(32, config(8, 2), vec![request(9, 5, 1, 1)], 8).await; + assert!(matches!( + ObservationDelta::between(first, other.last().unwrap()), + Err(DeltaError::PoolSizeChanged { .. }) + )); + + // Same pool size, more steps (60 decode tokens) but fewer admissions: the + // generation moves forward while the lifetime counter went backwards. + let fewer = run_and_snapshot(256, config(8, 2), vec![request(9, 5, 1, 60)], 80).await; + assert!(fewer.last().unwrap().generation > last.generation); + assert!(matches!( + ObservationDelta::between(last, fewer.last().unwrap()), + Err(DeltaError::CounterWentBackwards { + counter: "admitted_requests", + .. + }) + )); +} + +#[test] +fn zero_capacity_densities_are_none_not_zero() { + let kv = create_shared_kv_manager(0, 16); + let cfg = SchedulerConfig { + max_batch_size: 0, + max_batch_tokens: 0, + max_prefill_tokens: 0, + prefill_chunk_size: 0, + chunk_prefill: true, + watermark_blocks: 0, + }; + let scheduler = AienScheduler::new(cfg, kv.clone()); + let s = ServeObservationSnapshot::capture(&scheduler, &kv.read(), None, None); + assert_eq!(s.kv_total_blocks, 0); + assert_eq!(s.kv_block_density.value(), None); + assert_eq!(s.kv_sharing_density.value(), None); + assert_eq!(s.running_slot_density.value(), None); + assert_eq!(s.batch_slot_density.value(), None); + assert_eq!(s.batch_token_density.value(), None); + assert!(!s.kv_below_watermark); + assert_eq!(s.last_step, None); + assert_eq!(s.last_batch, None); + assert_conserved(&s, "zero capacity"); +} + +#[test] +fn batch_reading_copies_sizes_and_the_token_sum() { + let kv = create_shared_kv_manager(16, 16); + let scheduler = AienScheduler::new(config(4, 1), kv.clone()); + let batch = ScheduledBatch { + prefill_requests: vec![request(1, 10, 1, 1), request(2, 5, 1, 1)], + decode_requests: vec![3, 4, 5], + block_tables: Default::default(), + step_id: 42, + }; + let s = ServeObservationSnapshot::capture(&scheduler, &kv.read(), None, Some(&batch)); + let b = s.last_batch.unwrap(); + assert_eq!(b.step_id, 42); + assert_eq!(b.prefill_requests, 2); + assert_eq!(b.decode_requests, 3); + assert_eq!(b.batch_tokens, 15 + 3); + assert_eq!(s.batch_slot_density.value(), Some(5.0 / 4.0)); + assert_eq!(s.batch_token_density.value(), Some(18.0 / 1024.0)); +} + +#[test] +fn snapshot_serializes_and_round_trips() { + let kv = create_shared_kv_manager(8, 16); + let scheduler = AienScheduler::new(config(4, 1), kv.clone()); + let s = ServeObservationSnapshot::capture(&scheduler, &kv.read(), None, None); + let json = serde_json::to_string(&s).unwrap(); + let back: ServeObservationSnapshot = serde_json::from_str(&json).unwrap(); + assert_eq!(back, s); +} diff --git a/docs/campaigns/dual/2026-10-04-macro-snapshot-receipt.md b/docs/campaigns/dual/2026-10-04-macro-snapshot-receipt.md new file mode 100644 index 00000000..36be650e --- /dev/null +++ b/docs/campaigns/dual/2026-10-04-macro-snapshot-receipt.md @@ -0,0 +1,109 @@ +# Receipt: DUAL serve observation snapshot (read-only macroscopic adapter, DUAL-3a) + +Program: ARCH-0031 "DUAL, Constraint Pricing for Soft Resource Budgets". +Deliverable: an immutable snapshot of the serve path built only from existing +exact counters, with normalized densities and exact deltas, for DUAL +observation. Companion to the `serve.admit_preempt` decision observer +(`2026-10-04-serve-observer-receipt.md`); independent of it (no shared code, +no dependency on that branch). + +**Gate verdict: none claimed.** `DUAL_ADVISORY_SCHEDULER` is NOT claimed +PASS. No snapshot field is an authority input anywhere; nothing here can +change a scheduling, admission, preemption or KV decision. + +## 1. Identity + +| Field | Value | +|---|---| +| Repository | `aien-dev/aien-sovereign-core` | +| Base commit (GitHub `main`) | `91fba8fc0f00fd09fc3e9a6137522af3ae79c4e1` | +| Branch | `dual/macro-snapshot` (from `main`, not stacked) | +| Tree | clean at each recorded command | +| Compiler | `rustc 1.98.1 (48a229cea 2026-09-01)`, `cargo 1.98.1 (797e8a9bc 2026-08-05)` | +| Build config | `dev` profile (as CI) | +| Host | NVIDIA DGX Spark, GB10, aarch64, Linux 7.0.0-1019-nvidia, 20 CPUs | +| GPU exercised | **No.** Tests run `MockInferenceBackend` on the host CPU. | + +## 2. What changed + +New crate `crates/aien-dual-observation` (registered in the workspace +members list; `Cargo.lock` gains its entry). It depends on `aien-scheduler`, +`aien-kv-cache`, `aien-abi-core` and `serde` only, and reads them through +`&AienScheduler`, `&AienKvManager`, `&StepMetrics`, `&ScheduledBatch`. +Living in its own crate means it can reach only public counters; it cannot +touch scheduler or KV internals by construction. No existing crate changed. + +Types (`src/lib.rs`): + +- `Density { numerator, denominator }` with `value() -> Option`: + `None` when `denominator == 0`. Every quotient in the crate is one of these. +- `StepReading` (from `StepMetrics`, timing field left out), `BatchReading` + (from `ScheduledBatch`: counts and the token sum the scheduler compares to + `max_batch_tokens`). +- `ServeObservationSnapshot::capture(&scheduler, &kv, last_step, last_batch)`. + Every field's doc names its source counter: `SchedulerMetrics::total_steps` + (generation), `waiting_count`, `preempted_count`, `running_count`, + `SequenceArena::active_count`, the six `SchedulerMetrics` lifetime + counters, three `SchedulerConfig` limits, `total_block_count`, + `available_blocks`, `allocated_block_count`, `active_sequence_count`, the + six `KvMetrics` fields, the pool half of the watermark predicate, and five + densities (`kv_block`, `kv_sharing`, `running_slot`, `batch_slot`, + `batch_token`). +- `ObservationDelta::between(earlier, later)`: exact differences (steps, + arrivals = `admitted_requests` diff, completions, preemptions, prefill and + decode tokens, signed changes of allocated blocks, running and waiting). + Refuses a reversed generation, a lifetime counter that went backwards, or a + different pool size (`DeltaError`). + +No interpolation, no estimate, no state kept between calls, no new state +machine. The scheduler's own `step_id` is private and is not duplicated; the +generation is the existing `total_steps` counter (documented). + +## 3. Tests + +`crates/aien-dual-observation/tests/snapshot_conservation.rs` runs the real +`AienScheduler` and `AienKvManager` with the mock backend through a mixed +workload (admission, 150-token chunked prefill, completion) and a watermark +pressure workload (6-block pool, watermark 3, one preemption), snapshotting +after every submit and every step, and asserts at every snapshot: + +| Ledger check | Exact statement | +|---|---| +| KV partition | `physical_pages (ref_count>0) + free_blocks == total_blocks`; `allocated + free == total`; `used_blocks == physical_pages`; `shared + private == physical`; `logical >= physical` | +| Sequence state machine | `arena_active == running + waiting + preempted` | +| Lifetime ledger | `admitted_requests == finished_requests + running + waiting + preempted` (workload submits only through `submit_request`, never cancels; fork children via `fork_sequence` and cancellation are the documented cases where this denominator does not apply) | +| Step reading | `StepMetrics::active_kv_blocks == allocated_block_count` right after the step | +| Densities | numerators and denominators equal the named counters; `kv_below_watermark == free < watermark` | + +Plus: deltas equal counter differences and sum over consecutive snapshots to +the whole (arrivals 5, completions 5, prefill tokens 274 = submitted prompt +tokens); refusals for reversed order, foreign pool size and a counter that +went backwards; zero-capacity scheduler (0 blocks, batch size 0): every +density is `None`, not 0; `BatchReading` token sum; serde round trip. + +Commands and results are in §5. + +## 4. Limits + +- Mock backend, host CPU, no GPU, no real model. +- The snapshot is a point reading; the caller supplies `last_step` and + `last_batch` because the scheduler does not retain them. A capture with + `None` for both still holds every counter. +- `generation` is `total_steps` (steps that executed a batch), not the + scheduler's private per-call `step_id`. + +## 5. Run log + +| Command | Result | +|---|---| +| `cargo test -p aien-dual-observation` | 8 passed, 0 failed (1 unit: zero-denominator rule; 7 integration: ledgers close at every snapshot under plenty and under watermark pressure, deltas exact and additive, reversed / foreign / backwards refused, zero-capacity densities `None`, batch reading sums, serde round trip) | +| `cargo clippy -p aien-dual-observation --all-targets -- -D warnings` | exit 0 | +| `cargo fmt --all -- --check` | exit 0 | +| `cargo check --workspace --all-targets` | Finished (new member builds with the workspace) | +| `crumb compile .` then `crumb verify .` before the commit | see commit; the post-commit STALE reading of the root crumb is the tool's `generated_at_commit` behaviour, also present on pristine `main` (documented in the observer receipt §9.1 T7) | + +Negative control (by construction): the crate holds `&AienScheduler` and +`&AienKvManager` only; there is no `&mut` path and no return value the +scheduler reads. Nothing to inject. + +Candidate commit: the commit carrying this file (see the PR).