diff --git a/core/continuum-cognition/src/cognition/working_set.rs b/core/continuum-cognition/src/cognition/working_set.rs index f1144a0a36..3d14f6ac24 100644 --- a/core/continuum-cognition/src/cognition/working_set.rs +++ b/core/continuum-cognition/src/cognition/working_set.rs @@ -918,20 +918,22 @@ pub fn requirements_for( .iter() .map(|p| { let demand = working_set.demand_of(*p); - let wish = demand - .as_ref() - .map(requirement_tokens) - .unwrap_or(0); // JUSTIFIED unwrap_or: a mind with no turn yet is Unknown to the allocator (0 = no measurement, never a number) - let need = demand - .as_ref() - .and_then(need_tokens) - .unwrap_or(0); // JUSTIFIED unwrap_or: no held turn measured = no floor beyond the target (0 = no measurement) + use crate::inference::planning::window_allocator::{LaneRequirement, Tokens}; + // Measured or not, as a type: no turn yet is unmeasured, never a zero standing in for one. + let wish = demand.as_ref().and_then(|d| Tokens::new(requirement_tokens(d))); + let need = demand.as_ref().and_then(need_tokens).and_then(Tokens::new); // Her parked training examples' reservation, carried beside her conversational target // and need (card ea157b1a): the allocator grows toward it only from spare budget. let training = crate::genome::fine_tuning::training_demand::TrainingDemand::for_persona(*p).reservation(); - crate::inference::planning::window_allocator::LaneRequirement::from_demand(*p, wish, crate::inference::planning::serving_plan::SENT_HEADROOM) - .with_need(need) - .with_training(training) + let measured = match wish { + None => LaneRequirement::unmeasured(*p), + Some(wish) => LaneRequirement::wished(*p, wish, crate::inference::planning::serving_plan::SENT_HEADROOM), + }; + match need { + Some(need) => measured.held(need), + None => measured, + } + .with_training(training) }) .collect() } diff --git a/core/continuum-engine/src/capacity/window_grant.rs b/core/continuum-engine/src/capacity/window_grant.rs index 9d0dc56321..5224d0c5c6 100644 --- a/core/continuum-engine/src/capacity/window_grant.rs +++ b/core/continuum-engine/src/capacity/window_grant.rs @@ -16,6 +16,8 @@ use std::collections::BTreeMap; +use crate::inference::planning::window_allocator::Tokens; + /// What the serving daemon grants the local minds on its engine's pool, each by her persona id. /// Published on every tick that moves a grant; a mind's binding follows hers. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -26,9 +28,6 @@ pub struct PoolGrants { /// window), a slot's window on fixed slots. No grant exceeds it. pub per_sequence_cap: u32, pub by_mind: BTreeMap, - /// The minds whose requirement is not their own measurement yet but the population's (the - /// median measured requirement on the seat), marked so no reader takes it for hers. - pub from_population: std::collections::BTreeSet, } impl PoolGrants { @@ -52,12 +51,17 @@ pub fn current_grant(persona: uuid::Uuid) -> Option { GRANTS.get()?.borrow().as_ref()?.grant_for(persona) } -/// One mind's current demand on the pool: what her next turn requires, and whether a turn of hers -/// is in flight now. +/// One measured mind's current demand on the pool: her floor and target, and whether a turn of hers +/// is in flight now. A mind not measured yet has no `Demand`: there is no number to grant her +/// (`Measure::Unmeasured`), and her first view measures her. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Demand { pub mind: K, - pub required_tokens: u32, + /// The least her turn holds: below it she cannot think (the median of her held turns, else her + /// wish). Never trimmed here; a need above what one sequence holds waits. + pub need: Tokens, + /// What she would read whole (her wish with headroom), granted when the pool holds every target. + pub target: Tokens, pub in_flight: bool, /// The most she may be granted: what one sequence of the engine can hold. pub ceiling: u32, @@ -98,9 +102,9 @@ impl WindowPolicy for DemandFollowing { // waits). A holder whose need outgrew it keeps what she holds as her need: her binding stays // counted, so it can never be bound beside the pool uncounted (Cormac on #5745: A holding 40k, // need 70k, dropped while B was granted 60k bound 100k on a 65,536 pool). - let need = |d: &Demand| match d.required_tokens > d.ceiling { + let need = |d: &Demand| match d.need.get() > d.ceiling { true => holds(d), - false => d.required_tokens, + false => d.need.get(), }; let demands: Vec<&Demand> = demands.iter().filter(|d| need(d) > 0).collect(); let demands = demands.as_slice(); @@ -109,6 +113,12 @@ impl WindowPolicy for DemandFollowing { let want = |d: &Demand| need(d).max(holds(d)); let total = |f: &dyn Fn(&Demand) -> u32| demands.iter().map(|d| u64::from(f(d))).sum::(); let pool = u64::from(pool_tokens); + // Room for every target: each mind reads whole, never past one sequence, never below what she + // holds. Otherwise needs first, and what is left stays in the pool. + let aim = |d: &Demand| d.target.get().min(d.ceiling).max(want(d)); + if total(&aim) <= pool { + return demands.iter().map(|d| (d.mind, aim(d))).collect(); + } if total(&want) <= pool { return demands.iter().map(|d| (d.mind, want(d))).collect(); } @@ -162,8 +172,11 @@ impl WindowPolicy for DemandFollowing { mod tests { use super::*; - fn demand(mind: u32, required_tokens: u32, in_flight: bool, ceiling: u32) -> Demand { - Demand { mind, required_tokens, in_flight, ceiling } + use crate::inference::planning::window_allocator::test_tokens as t; + + /// A mind whose need is her target (a wish with no held turn yet). + fn demand(mind: u32, need: u32, in_flight: bool, ceiling: u32) -> Demand { + Demand { mind, need: t(need), target: t(need), in_flight, ceiling } } // what this catches: a window divided by a count (Joel, 2026-11-03: "What a mind needs not what @@ -262,4 +275,21 @@ mod tests { assert!(bound <= u64::from(pool), "bound {bound} on a {pool} pool: {grants:?}"); } + + // what this catches (the M5, 2026-11-03, b7c815484): grants sized from her wish instead of her + // need. Benchy's wish took the model's whole 262,144 of a 524,288 pool, Aiko's 104,015 and + // Aris's 88,380, and Atlas got nothing. Needs are granted first; targets only when every target + // fits. + #[test] + fn needs_are_granted_before_any_target_and_targets_only_when_all_fit() { + let pool = 524_288; + let mind = |m, need, target| Demand { mind: m, need: t(need), target: t(target), in_flight: false, ceiling: 262_144 }; + let wishes = [mind(1, 70_000, 262_144), mind(2, 60_000, 104_015), mind(3, 50_000, 88_380), mind(4, 40_000, 90_000)]; + let grants = DemandFollowing.grant(&wishes, &BTreeMap::new(), pool); + assert_eq!(grants, BTreeMap::from([(1, 70_000), (2, 60_000), (3, 50_000), (4, 40_000)]), "every need, no target: the targets sum past the pool"); + let modest = [mind(1, 70_000, 100_000), mind(2, 60_000, 104_015), mind(3, 50_000, 88_380), mind(4, 40_000, 90_000)]; + let grants = DemandFollowing.grant(&modest, &BTreeMap::new(), pool); + assert_eq!(grants, BTreeMap::from([(1, 100_000), (2, 104_015), (3, 88_380), (4, 90_000)]), "every target fits: each reads whole"); + } + } diff --git a/core/continuum-engine/src/capacity/window_sim.rs b/core/continuum-engine/src/capacity/window_sim.rs index 269e5e81e4..98c47f8e1d 100644 --- a/core/continuum-engine/src/capacity/window_sim.rs +++ b/core/continuum-engine/src/capacity/window_sim.rs @@ -17,6 +17,21 @@ use std::collections::BTreeMap; +use crate::inference::planning::window_allocator::Tokens; + +/// A scenario's literal token count, checked nonzero when the scenario compiles: a zero literal is a +/// compile error, never a runtime fallback. +macro_rules! tokens { + ($n:expr) => { + const { + match Tokens::new($n) { + Some(tokens) => tokens, + None => panic!("a scenario's token literal is never zero"), + } + } + }; +} + /// A mind on the pool (a resident, or the scratch traffic beside them). pub type MindId = u32; @@ -26,7 +41,8 @@ pub type MindId = u32; pub struct DemandEvent { pub at_ms: u64, pub mind: MindId, - pub required_tokens: u32, + /// Her need, which is her target in the sim (a wish with no held turn). + pub need: Tokens, pub in_flight: bool, } @@ -68,7 +84,8 @@ pub fn run(scenario: &WindowScenario, policy: &mut dyn WindowPolicy) -> event.mind, Demand { mind: event.mind, - required_tokens: event.required_tokens, + need: event.need, + target: event.need, in_flight: event.in_flight, // the shared pool: one sequence may hold all of it ceiling: scenario.pool_tokens, @@ -89,7 +106,7 @@ pub fn run(scenario: &WindowScenario, policy: &mut dyn WindowPolicy) -> true => held.get(&d.mind).copied().unwrap_or(0), // unwrap_or: a turn that holds nothing yet is owed only her demand false => 0, }; - u64::from(d.required_tokens.max(floor)) + u64::from(d.need.get().max(floor)) }; let demanded: u64 = current.iter().map(owed).sum(); // Granted past what is owed: room an idle mind holds that a reading mind could have used. @@ -109,7 +126,7 @@ pub fn run(scenario: &WindowScenario, policy: &mut dyn WindowPolicy) -> { out.in_flight_shrinks += 1; } - if granted < demand.required_tokens { + if granted < demand.need.get() { if demanded <= u64::from(scenario.pool_tokens) { out.unmet_when_fits += 1; } @@ -150,24 +167,24 @@ pub fn m5_uneven_reading() -> WindowScenario { const ATLAS: MindId = 3; const BENCHY: MindId = 4; const SCRATCH: MindId = 5; - let e = |at_ms, mind, required_tokens, in_flight| DemandEvent { + let e = |at_ms, mind, need, in_flight| DemandEvent { at_ms, mind, - required_tokens, + need, in_flight, }; WindowScenario { name: "m5-uneven-reading", pool_tokens: 290_560, events: vec![ - e(0, ATLAS, 12_000, false), - e(1, ARIS, 40_000, true), - e(2, BENCHY, 52_000, true), - e(3, SCRATCH, 1_000, true), - e(4, AIKO, 70_000, true), - e(5, AIKO, 76_000, true), - e(6, ATLAS, 9_000, false), - e(7, BENCHY, 58_000, true), + e(0, ATLAS, tokens!(12_000), false), + e(1, ARIS, tokens!(40_000), true), + e(2, BENCHY, tokens!(52_000), true), + e(3, SCRATCH, tokens!(1_000), true), + e(4, AIKO, tokens!(70_000), true), + e(5, AIKO, tokens!(76_000), true), + e(6, ATLAS, tokens!(9_000), false), + e(7, BENCHY, tokens!(58_000), true), ], } } @@ -201,11 +218,11 @@ mod tests { // because her demand fell mid-turn; the grant she is using holds until the turn ends. #[test] fn a_turn_in_flight_keeps_its_grant_when_her_demand_falls_and_everything_fits() { - let e = |at_ms, mind, required_tokens, in_flight| DemandEvent { at_ms, mind, required_tokens, in_flight }; + let e = |at_ms, mind, need, in_flight| DemandEvent { at_ms, mind, need, in_flight }; let scenario = WindowScenario { name: "falling-demand-in-flight", pool_tokens: 100_000, - events: vec![e(0, 1, 60_000, true), e(1, 1, 30_000, true), e(2, 2, 20_000, false)], + events: vec![e(0, 1, tokens!(60_000), true), e(1, 1, tokens!(30_000), true), e(2, 2, tokens!(20_000), false)], }; let run = run(&scenario, &mut DemandFollowing); assert!(run.kept(), "{run:?}"); @@ -216,11 +233,11 @@ mod tests { // fits 100k, the floors do not, so the neighbour's 40k is the pool's limit, not a breach. #[test] fn fits_and_slack_count_a_turn_in_flight_at_what_it_holds() { - let e = |at_ms, mind, required_tokens, in_flight| DemandEvent { at_ms, mind, required_tokens, in_flight }; + let e = |at_ms, mind, need, in_flight| DemandEvent { at_ms, mind, need, in_flight }; let scenario = WindowScenario { name: "held-floor-beside-a-big-neighbour", pool_tokens: 100_000, - events: vec![e(0, 1, 60_000, true), e(1, 1, 30_000, true), e(2, 2, 50_000, false)], + events: vec![e(0, 1, tokens!(60_000), true), e(1, 1, tokens!(30_000), true), e(2, 2, tokens!(50_000), false)], }; let run = run(&scenario, &mut DemandFollowing); assert!(run.kept(), "{run:?}"); @@ -229,19 +246,19 @@ mod tests { // what this catches: an overloaded pool shrinking a turn in flight to seat another. #[test] fn an_overloaded_pool_never_shrinks_a_turn_in_flight() { - let e = |at_ms, mind, required_tokens, in_flight| DemandEvent { + let e = |at_ms, mind, need, in_flight| DemandEvent { at_ms, mind, - required_tokens, + need, in_flight, }; let scenario = WindowScenario { name: "overloaded", pool_tokens: 100_000, events: vec![ - e(0, 1, 60_000, true), - e(1, 2, 60_000, false), - e(2, 3, 30_000, false), + e(0, 1, tokens!(60_000), true), + e(1, 2, tokens!(60_000), false), + e(2, 3, tokens!(30_000), false), ], }; let run = run(&scenario, &mut DemandFollowing); diff --git a/core/continuum-engine/src/inference/planning/serving_plan/tests/mod.rs b/core/continuum-engine/src/inference/planning/serving_plan/tests/mod.rs index 4b87686ce3..6f65340d20 100644 --- a/core/continuum-engine/src/inference/planning/serving_plan/tests/mod.rs +++ b/core/continuum-engine/src/inference/planning/serving_plan/tests/mod.rs @@ -11,7 +11,7 @@ // the plan says so with fits_on_gpu=false instead of planning a 2k lane. #[test] pub(super) fn with_requirements_the_plan_is_the_allocators_never_a_starved_lane() { - use crate::inference::planning::window_allocator::LaneRequirement; + use crate::inference::planning::window_allocator::{test_tokens, LaneRequirement}; const GB: u64 = 1 << 30; let qwen = ModelFootprint { model_id: "qwen-27b".into(), @@ -23,8 +23,8 @@ }; let host = HostBudget { usable_bytes: 30 * GB, perf_cores: 8 }; let two = vec![ - LaneRequirement::declared(uuid::Uuid::new_v4(), 70_000), - LaneRequirement::declared(uuid::Uuid::new_v4(), 70_000), + LaneRequirement::declared(uuid::Uuid::new_v4(), test_tokens(70_000)), + LaneRequirement::declared(uuid::Uuid::new_v4(), test_tokens(70_000)), ]; // The poisoned inputs the 5090 had: a sent median of 828 and a sticky 2048. let demand = ServingDemand::new(2, Some(56_057)) @@ -35,7 +35,7 @@ assert_eq!((plan.lanes, plan.served_context_window), (2, 70_000), "{}", plan.rationale); assert!(plan.fits_on_gpu); - let five: Vec<_> = (0..5).map(|_| LaneRequirement::declared(uuid::Uuid::new_v4(), 70_000)).collect(); + let five: Vec<_> = (0..5).map(|_| LaneRequirement::declared(uuid::Uuid::new_v4(), test_tokens(70_000))).collect(); let squeezed = plan_serving(&host, std::slice::from_ref(&qwen), &ServingDemand::new(5, Some(56_057)).with_requirements(five)).expect("plan"); assert_eq!((squeezed.lanes, squeezed.served_context_window), (2, 70_000), "minds shed, window kept"); assert_eq!(squeezed.grid_overflow_lanes, 3); diff --git a/core/continuum-engine/src/inference/planning/window_allocator.rs b/core/continuum-engine/src/inference/planning/window_allocator.rs index e684364800..6caf039f97 100644 --- a/core/continuum-engine/src/inference/planning/window_allocator.rs +++ b/core/continuum-engine/src/inference/planning/window_allocator.rs @@ -43,42 +43,72 @@ use super::serving_plan::{HostBudget, ModelFootprint, MAX_LANES}; use uuid::Uuid; -/// Where a requirement came from — carried so a receipt can say whether the mind -/// declared it, the substrate measured it, or nothing was known. +/// A token count a mind's turns measured. Never zero: zero tokens is no measurement, and no +/// measurement is [`Measure::Unmeasured`], never a number. +pub type Tokens = std::num::NonZeroU32; + +/// A test's literal token count. A zero literal is a test bug, caught when the test runs; production +/// code has no way to make a token count from nothing. +#[cfg(any(test, feature = "test-fixtures"))] +pub const fn test_tokens(n: u32) -> Tokens { + match Tokens::new(n) { + Some(tokens) => tokens, + None => panic!("a test's token literal is never zero"), + } +} + +/// What a mind's turns have measured of what she requires of a lane. Nothing stands in for a +/// measurement that does not exist: an unmeasured mind is a variant with no number in it, so no +/// reader can size anything from her (Joel, 2026-11-03: "Undefined type values is how you do it. +/// And you require it to be set period"). #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] -#[serde(rename_all = "snake_case")] -pub enum RequirementSource { - /// Declared on the mind (her recipe/genome): the governed size. - Declared, - /// The untrimmed demand her turns assemble — what she NEEDS, never what a window - /// let her send. - MeasuredDemand, - /// No turn measured yet: resolved by the allocator to the largest requirement on - /// the seat, else the model's trained window (what fits at one lane). - Unknown, +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Measure { + /// No view assembled yet. Her wish is recorded when her first view is built, before she asks + /// for the engine, so she leaves this state without being served. + Unmeasured, + /// Her untrimmed assembly is measured (her TARGET, with headroom); no held turn has measured a + /// floor yet, so the target is the floor. + Wished { target: Tokens }, + /// A held turn measured her FLOOR: the median post-fit size of turns the fit held, no headroom. + /// `need <= target` (a floor never exceeds what it floors; the constructor enforces it). The + /// allocator never serves below the need, and serves the target when the budget holds it (card + /// 70706a9e: Kimi's wish 99k x 1.25 read as "over the grid" at a 75,776 seat her turns fitted + /// into every time; a requirement is a target, the need is the gate). + Held { need: Tokens, target: Tokens }, + /// Declared on the mind (her recipe or genome): the governed size, target and floor alike. + Declared { target: Tokens }, +} + +impl Measure { + /// Her target, when one is measured. + pub fn target(self) -> Option { + match self { + Self::Unmeasured => None, + Self::Wished { target } | Self::Held { target, .. } | Self::Declared { target } => Some(target), + } + } + + /// Her floor, when one is measured: the held need, else the target (a wish or a declaration is + /// its own floor). + pub fn need(self) -> Option { + match self { + Self::Unmeasured => None, + Self::Held { need, .. } => Some(need), + Self::Wished { target } | Self::Declared { target } => Some(target), + } + } } /// What one mind requires of a lane. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct LaneRequirement { pub persona: Uuid, - /// Tokens the lane must hold for one of her turns: prompt + completion reserve. - /// `None` = not yet measured (`RequirementSource::Unknown`). This is her TARGET — - /// the wish (untrimmed assembly) with headroom, or her declared size. - pub window: Option, - pub source: RequirementSource, - /// The FLOOR below which a lane starves her: the median post-fit size of turns the - /// fit HELD, no headroom (she was served at that size). `None` = no held turn - /// measured, and the target is the floor as before. The allocator never serves - /// below the need; it serves at the target when the budget holds it and at the - /// most it can hold ≥ need otherwise (card 70706a9e: Kimi's wish 99k × 1.25 read - /// as "over the grid" at a 75,776 seat her turns fitted into every time — - /// a requirement is a target, not a gate; the need is the gate). - #[serde(default)] - pub need: Option, + /// What her turns have measured: her target and floor, or nothing yet. + pub measure: Measure, /// Her parked training examples' reservation (card ea157b1a): the window that trains them - /// whole and the training graph it costs. Carried BESIDE her conversational `window` and - /// `need`, never folded into them: the allocator grows toward it only from what is left + /// whole and the training graph it costs. Carried BESIDE her conversational measure, never + /// folded into it: the allocator grows toward it only from what is left /// once the conversational geometry is packed, so learning can never mute her. pub training: Option, } @@ -140,18 +170,33 @@ impl TrainingReserve { } impl LaneRequirement { - /// A requirement from the untrimmed demand a mind assembles, with headroom. Zero - /// (no turn yet) is `Unknown`, never a number. The interim source until the - /// declared field is wired; the allocator does not distinguish. - pub fn from_demand(persona: Uuid, demand_tokens: u32, headroom: f64) -> Self { - if demand_tokens == 0 { - return Self { persona, window: None, source: RequirementSource::Unknown, need: None, training: None }; - } - Self { persona, window: Some((demand_tokens as f64 * headroom) as u32), source: RequirementSource::MeasuredDemand, need: None, training: None } + /// A mind with no view assembled yet: no number, nothing to size from. + pub fn unmeasured(persona: Uuid) -> Self { + Self { persona, measure: Measure::Unmeasured, training: None } + } + + /// Her measured wish (the untrimmed demand her view assembled) with headroom: her target. + pub fn wished(persona: Uuid, wish: Tokens, headroom: f64) -> Self { + // Headroom only adds: the target is the wish plus what headroom asks beyond it. + let beyond = ((f64::from(wish.get()) * headroom) as u32).saturating_sub(wish.get()); + Self { persona, measure: Measure::Wished { target: wish.saturating_add(beyond) }, training: None } } - pub fn declared(persona: Uuid, window: u32) -> Self { - Self { persona, window: Some(window), source: RequirementSource::Declared, need: None, training: None } + pub fn declared(persona: Uuid, window: Tokens) -> Self { + Self { persona, measure: Measure::Declared { target: window }, training: None } + } + + /// With the floor her held turns measured. A need above the target is clamped to it (a floor + /// cannot exceed what it floors); on an unmeasured mind a held need is both floor and target, + /// since she was served at that size. + pub fn held(mut self, need: Tokens) -> Self { + self.measure = match self.measure { + Measure::Unmeasured => Measure::Held { need, target: need }, + Measure::Wished { target } | Measure::Held { target, .. } | Measure::Declared { target } => { + Measure::Held { need: need.min(target), target } + } + }; + self } /// Carry her parked training examples' reservation (card ea157b1a). Her conversational @@ -163,36 +208,17 @@ impl LaneRequirement { self } - /// With her measured need (the floor); `0` = no held turn, no floor beyond the - /// target. A need above the target is clamped to it: a floor cannot exceed the - /// number it floors. - pub fn with_need(mut self, need_tokens: u32) -> Self { - self.need = (need_tokens > 0).then_some(match self.window { - Some(w) => need_tokens.min(w), - None => need_tokens, - }); - self - } - - /// The window this requirement resolves to: its own, else the largest known on - /// the seat, else the most `fp` can hold at `lanes` within `budget` (its trained - /// window bounded by the fit) — the honest cold start, not a number. - fn resolve(&self, largest_known: Option, fp: &ModelFootprint, budget: u64, lanes: u32) -> u32 { - self.window.or(largest_known).unwrap_or_else(|| fp.window_within(budget, lanes)) // unwrap_or_else: nothing measured on the seat = the most this model holds here, a fit not a constant - } - - /// The floor a lane must clear for her: the need when measured, else the resolved - /// target (the pre-70706a9e behaviour: with no held turn the wish is the gate). - fn floor(&self, target: u32) -> u32 { - self.need.map_or(target, |n| n.min(target)) + /// Her target and floor in tokens, when measured. An unmeasured mind has neither and is not + /// packed: she is measured by her first view, before she needs a lane. + fn sized(&self) -> Option<(u32, u32)> { + Some((self.measure.target()?.get(), self.measure.need()?.get())) } } -/// The largest requirement this seat KNOWS — what an `Unknown` resolves to before the -/// model's own trained window, and the window an undeclared grid role stands at. `None` -/// = nothing measured anywhere on the seat. +/// The largest target this seat has measured: the window an undeclared grid role stands at, and +/// the shared window's growth target. `None` = nothing measured anywhere on the seat. pub fn largest_known(requirements: &[LaneRequirement]) -> Option { - requirements.iter().filter_map(|r| r.window).max() + requirements.iter().filter_map(|r| r.measure.target()).map(Tokens::get).max() } /// The allocator's answer: one engine geometry and who it serves. @@ -236,18 +262,18 @@ fn device_bytes(fp: &ModelFootprint, window: u32, lanes: u32) -> u64 { /// requirements smallest-first, and keep adding a mind while the geometry /// (lanes = count, window = her requirement, the largest so far) still fits. /// Returns (served count, window) or None when not even one fits. -fn pack(fp: &ModelFootprint, sorted: &[&LaneRequirement], largest_known: Option, budget: u64, lane_cap: u32) -> Option<(u32, u32)> { +/// `sorted` holds measured minds only, as (target, floor), ascending by target. +fn pack(fp: &ModelFootprint, sorted: &[(u32, u32)], budget: u64, lane_cap: u32) -> Option<(u32, u32)> { let mut best: Option<(u32, u32)> = None; // ONE window serves every mind packed so far, so it must clear the highest floor // among them, not only the current mind's. let mut floor_so_far = 0u32; - for (i, req) in sorted.iter().enumerate() { + for (i, &(target, need)) in sorted.iter().enumerate() { let lanes = (i as u32) + 1; if lanes > lane_cap { break; } - let target = req.resolve(largest_known, fp, budget, lanes); - floor_so_far = floor_so_far.max(req.floor(target)); + floor_so_far = floor_so_far.max(need); // Serve at the target when the model and the budget hold it; otherwise at the // most this model holds for these lanes within the budget — but NEVER below // a floor. Below her floor a mind starves; between floor and target the fit @@ -285,19 +311,19 @@ pub fn allocate( if candidates.is_empty() { return Err(Unallocatable::NoCandidates); } - if requirements.is_empty() { + // Only measured minds are packed: an unmeasured one has no number to size from, and her first + // view measures her before she asks for a lane. + let mut sorted: Vec<(&LaneRequirement, (u32, u32))> = requirements.iter().filter_map(|r| Some((r, r.sized()?))).collect(); + sorted.sort_by_key(|(r, (target, _))| (*target, r.persona)); + let Some(&(_, (smallest_target, _))) = sorted.first() else { return Err(Unallocatable::NoRequirements); - } - // Unknowns resolve to the largest known requirement on the seat (they sort after - // it); with nothing known they resolve per candidate to its trained window. - let largest_known = largest_known(requirements); - let mut sorted: Vec<&LaneRequirement> = requirements.iter().collect(); - sorted.sort_by_key(|r| (r.window.unwrap_or(u32::MAX), r.persona)); + }; + let sizes: Vec<(u32, u32)> = sorted.iter().map(|(_, size)| *size).collect(); // The lane cap and what set it, chosen together (ties to the earlier term), so a caller can // tell a cap from a budget refusal (Codex on #4971): with more minds than `lane_cap`, the // unserved were never offered a lane, whatever the budget. let (lane_cap, lane_cap_by) = [ - (requirements.len() as u32, crate::inference::planning::serving_plan::LaneCapBy::Requirements), + (sorted.len() as u32, crate::inference::planning::serving_plan::LaneCapBy::Requirements), (budget.perf_cores.max(1), crate::inference::planning::serving_plan::LaneCapBy::Cores), (MAX_LANES, crate::inference::planning::serving_plan::LaneCapBy::MaxLanes), (max_lanes, crate::inference::planning::serving_plan::LaneCapBy::Demand), @@ -308,7 +334,7 @@ pub fn allocate( let mut best: Option<(&ModelFootprint, u32, u32)> = None; for fp in candidates { - let Some((lanes, window)) = pack(fp, &sorted, largest_known, budget.usable_bytes, lane_cap) else { continue }; + let Some((lanes, window)) = pack(fp, &sizes, budget.usable_bytes, lane_cap) else { continue }; let better = match best { None => true, Some((b, bl, _)) => { @@ -323,7 +349,7 @@ pub fn allocate( let Some((fp, lanes, window)) = best else { return Err(Unallocatable::NothingFitsOneLane { budget_bytes: budget.usable_bytes, - smallest_requirement: largest_known.unwrap_or(0), // unwrap_or: nothing measured = 0 in the receipt, "unknown" spelled as the number it is + smallest_requirement: smallest_target, }); }; // Packing decides how many warm slots fit. Queued minds still use those slots @@ -332,8 +358,14 @@ pub fn allocate( let (window, training_growth) = grow_shared_window( requirements, fp, budget.usable_bytes, lanes, window, ); - let served: Vec = sorted.iter().take(lanes as usize).map(|r| r.persona).collect(); - let unserved: Vec = sorted.iter().skip(lanes as usize).map(|r| r.persona).collect(); + let served: Vec = sorted.iter().take(lanes as usize).map(|(r, _)| r.persona).collect(); + // Unserved: the measured minds packing left out, then the unmeasured, who wait for their first view. + let unserved: Vec = sorted + .iter() + .skip(lanes as usize) + .map(|(r, _)| r.persona) + .chain(requirements.iter().filter(|r| r.sized().is_none()).map(|r| r.persona)) + .collect(); Ok(Allocation { model_id: fp.model_id.clone(), capability_rank: fp.capability_rank, @@ -404,6 +436,8 @@ fn grow_shared_window( mod tests { use super::*; + use super::test_tokens as t; + const GB: u64 = 1 << 30; /// The 27B the 5090 and the M5 serve: 19 GB of weights, ~33 KB/token KV (2.2 GB @@ -435,7 +469,7 @@ mod tests { } fn minds(windows: &[u32]) -> Vec { - windows.iter().map(|w| LaneRequirement::declared(Uuid::new_v4(), *w)).collect() + windows.iter().map(|w| LaneRequirement::declared(Uuid::new_v4(), t(*w))).collect() } // What this catches: training demand must reserve each job once without @@ -463,12 +497,12 @@ mod tests { // must not be reserved twice, while an uncovered remainder still is. let mut charged = reserve.clone(); charged.account_charged_bytes(bytes); - let charged_reqs = [LaneRequirement::declared(Uuid::new_v4(), baseline) + let charged_reqs = [LaneRequirement::declared(Uuid::new_v4(), t(baseline)) .with_training(Some(charged.clone()))]; assert_eq!(grow_shared_window(&charged_reqs, &fp, roomy - bytes, 1, baseline), (target, TrainingGrowth::Reserved { bytes: 0, target, reached: true })); charged.account_charged_bytes(bytes / 2); - let partial_reqs = [LaneRequirement::declared(Uuid::new_v4(), baseline) + let partial_reqs = [LaneRequirement::declared(Uuid::new_v4(), t(baseline)) .with_training(Some(charged))]; assert_eq!(grow_shared_window(&partial_reqs, &fp, roomy - bytes / 2, 1, baseline), (target, TrainingGrowth::Reserved { bytes: bytes / 2, target, reached: true })); @@ -479,10 +513,10 @@ mod tests { TrainingReserve::new(target, None, None), TrainingReserve::new(target, Some(TrainingPrice { model: "other-base".into(), ..price }), Some(Uuid::from_u128(7))), ] { - let reqs = [LaneRequirement::declared(Uuid::new_v4(), 55_000).with_training(Some(unknown.clone()))]; + let reqs = [LaneRequirement::declared(Uuid::new_v4(), t(55_000)).with_training(Some(unknown.clone()))]; assert_eq!(grow_shared_window(&reqs, &fp, roomy, 1, baseline), (55_000, TrainingGrowth::Unmeasured { reserved_bytes: 0 })); - let mixed = [reqs[0].clone(), LaneRequirement::declared(Uuid::new_v4(), baseline) + let mixed = [reqs[0].clone(), LaneRequirement::declared(Uuid::new_v4(), t(baseline)) .with_training(Some(reserve.clone()))]; assert_eq!(grow_shared_window(&mixed, &fp, partial, 1, baseline), (50_000, TrainingGrowth::Unmeasured { reserved_bytes: bytes })); @@ -603,25 +637,21 @@ mod tests { assert_eq!((roomy.lanes, roomy.window), (3, 256_000), "with room, all three at the largest requirement"); } - // what this catches: there is NO constant floor (Joel: "you're hard coding - // constants again"). A mind with no turn yet is Unknown — it resolves to the - // largest requirement on the seat, and with nothing known on the seat to the - // model's own trained window, which the budget then bounds at one lane. A - // measured demand is the requirement, with headroom, whatever its size. + // what this catches: a number standing in for a mind not measured yet (Joel, 2026-11-03: "use + // nothing not constants. Undefined type values is how you do it"). She was resolved to the seat's + // largest requirement or the model's whole window; now she has no number and is not packed: the + // measured minds are sized, she is unserved until her first view measures her, and a seat with + // nobody measured has no requirement at all (never a fit or a borrowed size). #[test] - fn an_unmeasured_mind_resolves_to_the_seat_or_the_model_never_a_constant() { - let unknown = LaneRequirement::from_demand(Uuid::new_v4(), 0, 1.25); - assert_eq!((unknown.window, unknown.source), (None, RequirementSource::Unknown)); - let measured = LaneRequirement::from_demand(Uuid::new_v4(), 56_057, 1.25); - assert_eq!(measured.window, Some(70_071)); - // Beside a measured 70k coder, the unknown takes 70k: two lanes at 70k. + fn an_unmeasured_mind_is_never_sized_from_anything_but_her_own_measure() { + let unknown = LaneRequirement::unmeasured(Uuid::new_v4()); + assert_eq!((unknown.measure.target(), unknown.measure.need()), (None, None)); + let measured = LaneRequirement::wished(Uuid::new_v4(), t(56_057), 1.25); + assert_eq!(measured.measure, Measure::Wished { target: t(70_071) }); let a = allocate(&[measured.clone(), unknown.clone()], &[qwen27b()], &budget(30), u32::MAX).expect("fits"); - assert_eq!((a.lanes, a.window), (2, 70_071)); - // Alone, the unknown takes the model's trained window bounded by one lane's fit: - // the 27B in 30 GB holds ~ (30-19) GB / per-token cost — far above any floor. - let alone = allocate(&[unknown], &[qwen27b()], &budget(30), u32::MAX).expect("fits"); - assert_eq!(alone.lanes, 1); - assert!(alone.window > 200_000, "the trained window, not a constant: {}", alone.window); + assert_eq!((a.lanes, a.window, a.served.clone()), (1, a.window, vec![measured.persona]), "only the measured mind is packed"); + assert_eq!(a.unserved, vec![unknown.persona], "the unmeasured mind waits for her first view, unsized"); + assert!(matches!(allocate(&[unknown], &[qwen27b()], &budget(30), u32::MAX), Err(Unallocatable::NoRequirements)), "nobody measured: nothing to allocate for"); } // what this catches: the model is shed before the roster is — a box that cannot @@ -656,7 +686,7 @@ mod tests { let one_lane = q8.window_within(budget(22).usable_bytes, 1); assert!(one_lane > 40_000 && one_lane < 90_000, "precondition: one 27B lane on this card is tens of k, not hundreds: {one_lane}"); let kimi = one_lane - 1_000; - let seat = vec![LaneRequirement::declared(Uuid::new_v4(), kimi), LaneRequirement::declared(Uuid::new_v4(), 97_268)]; + let seat = vec![LaneRequirement::declared(Uuid::new_v4(), t(kimi)), LaneRequirement::declared(Uuid::new_v4(), t(97_268))]; let a = allocate(&seat, &[q8, small7b()], &budget(22), u32::MAX).expect("fits"); assert_eq!((a.model_id.as_str(), a.lanes, a.window), ("qwen-27b", 1, one_lane)); assert_eq!(a.unserved.len(), 1); @@ -674,26 +704,26 @@ mod tests { let budget = HostBudget { usable_bytes: device_bytes(&fp, 80_000, 1), perf_cores: 8 }; assert!(fp.window_within(budget.usable_bytes, 1) < 123_870 && fp.window_within(budget.usable_bytes, 1) >= 74_000, "fixture premise"); let kimi = Uuid::new_v4(); - let wish_only = [LaneRequirement::from_demand(kimi, 99_096, 1.25)]; - let sorted: Vec<&LaneRequirement> = wish_only.iter().collect(); - assert_eq!(pack(&fp, &sorted, largest_known(&wish_only), budget.usable_bytes, 4), None, "no need: the target is the floor, the budget cannot hold 123,870, she is shed (pre-70706a9e behaviour)"); + let wish_only = [LaneRequirement::wished(kimi, t(99_096), 1.25)]; + let sorted: Vec<(u32, u32)> = wish_only.iter().filter_map(LaneRequirement::sized).collect(); + assert_eq!(pack(&fp, &sorted, budget.usable_bytes, 4), None, "no need: the target is the floor, the budget cannot hold 123,870, she is shed (pre-70706a9e behaviour)"); - let with_need = [LaneRequirement::from_demand(kimi, 99_096, 1.25).with_need(74_000)]; - let sorted: Vec<&LaneRequirement> = with_need.iter().collect(); - let (lanes, window) = pack(&fp, &sorted, largest_known(&with_need), budget.usable_bytes, 4).expect("served"); + let with_need = [LaneRequirement::wished(kimi, t(99_096), 1.25).held(t(74_000))]; + let sorted: Vec<(u32, u32)> = with_need.iter().filter_map(LaneRequirement::sized).collect(); + let (lanes, window) = pack(&fp, &sorted, budget.usable_bytes, 4).expect("served"); assert_eq!(lanes, 1); - assert!(window >= 74_000 && window < 123_870, "served between need and target at what the budget holds: {window}"); + assert!((74_000..123_870).contains(&window), "served between need and target at what the budget holds: {window}"); assert_eq!(window, fp.window_within(budget.usable_bytes, 1), "the window is the most the model holds here, not a constant"); // A second mind whose floor is her target: the one shared window must clear it. let aiko = Uuid::new_v4(); let two = [ - LaneRequirement::from_demand(aiko, 24_226, 1.0), - LaneRequirement::from_demand(kimi, 99_096, 1.25).with_need(74_000), + LaneRequirement::wished(aiko, t(24_226), 1.0), + LaneRequirement::wished(kimi, t(99_096), 1.25).held(t(74_000)), ]; - let mut sorted: Vec<&LaneRequirement> = two.iter().collect(); - sorted.sort_by_key(|r| (r.window.unwrap_or(u32::MAX), r.persona)); - let (lanes, window) = pack(&fp, &sorted, largest_known(&two), budget.usable_bytes, 4).expect("at least aiko"); + let mut sorted: Vec<(u32, u32)> = two.iter().filter_map(LaneRequirement::sized).collect(); + sorted.sort_unstable(); + let (lanes, window) = pack(&fp, &sorted, budget.usable_bytes, 4).expect("at least aiko"); assert!(window >= 24_226, "aiko's floor is her target and the shared window clears it: {window}"); if lanes == 2 { assert!(window >= 74_000, "if kimi is packed too the shared window clears her need: {window}"); @@ -709,16 +739,15 @@ mod tests { let job = Uuid::from_u128(0x1e02); let price = TrainingPrice { bytes: 6_000_000_000, source: crate::inference::planning::training_plan::NeedSource::LowerBound, model: "kimi-base".into(), shape: "kimi-base|w64256|r8|attn_q,attn_v|exact|rc".into() }; let measured = TrainingReserve::new(64_256, Some(price.clone()), Some(job)); - for her in [LaneRequirement::from_demand(Uuid::new_v4(), 40_000, 1.25).with_need(30_000), LaneRequirement::from_demand(Uuid::new_v4(), 40_000, 1.25)] { + for her in [LaneRequirement::wished(Uuid::new_v4(), t(40_000), 1.25).held(t(30_000)), LaneRequirement::wished(Uuid::new_v4(), t(40_000), 1.25)] { let learning = her.clone().with_training(Some(measured.clone())); - assert_eq!((learning.window, learning.need, learning.source), (her.window, her.need, her.source), "conversation untouched"); - assert_eq!(learning.floor(50_000), her.floor(50_000), "no held turn or one: her floor is her conversation's, never the training window"); + assert_eq!(learning.measure, her.measure, "conversation untouched: her target and floor are her conversation's, never the training window"); assert_eq!(learning.training.as_ref(), Some(&measured), "the reservation travels to the allocator, its source labeled"); } assert_eq!(measured.price_for("kimi-base"), Some(&price), "priced for the model it was measured on"); assert_eq!(measured.price_for("another-base"), None, "the same window on another model is unmeasured, never this price"); assert_eq!(TrainingReserve::new(64_256, None, None).price_for("kimi-base"), None); - let her = LaneRequirement::from_demand(Uuid::new_v4(), 40_000, 1.25); + let her = LaneRequirement::wished(Uuid::new_v4(), t(40_000), 1.25); assert_eq!(her.clone().with_training(Some(TrainingReserve::new(0, Some(price), Some(job)))), her, "a zero window reserves nothing"); assert_eq!(her.clone().with_training(None), her, "nothing parked, nothing changes"); } diff --git a/core/continuum-engine/src/inference/served_window_store.rs b/core/continuum-engine/src/inference/served_window_store.rs index e3e13e3f67..9a426688eb 100644 --- a/core/continuum-engine/src/inference/served_window_store.rs +++ b/core/continuum-engine/src/inference/served_window_store.rs @@ -173,16 +173,25 @@ fn observe_to(path: &Path, geometry: &ServedGeometry, tokens: u32) { stored.set_at_ms = continuum_base::time::EpochMs::now().millis(); write_record(path, &stored); } +/// Place the record through the one durable primitive: staged in its directory, synced, renamed +/// over the old one, so a crash leaves the previous record or the new one, never a torn file. +fn place(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else { + return Err(std::io::Error::other(format!("{} names no file in a directory", path.display()))); + }; + std::fs::create_dir_all(dir)?; + let mut staged = continuum_host::durable::Staging::new_in(dir)?; + staged.write_all(bytes)?; + staged.replace(Path::new(name)) +} + fn write_record(path: &Path, stored: &StoredServedWindow) { let model_id = stored.model_id.as_str(); let per_slot_window = stored.per_slot_window; let lanes = stored.lanes; let typical_prompt_tokens = stored.typical_prompt_tokens; - if let Some(parent) = path.parent() { - let _ = std::fs::create_dir_all(parent); - } - match serde_json::to_vec_pretty(&stored).map(|b| std::fs::write(path, b)) { - Ok(Ok(())) => continuum_base::probe!( + match serde_json::to_vec_pretty(&stored).map_err(std::io::Error::other).and_then(|bytes| place(path, &bytes)) { + Ok(()) => continuum_base::probe!( class = "serving.window.stored", model = model_id, per_slot_window = per_slot_window as u64, @@ -190,9 +199,10 @@ fn write_record(path: &Path, stored: &StoredServedWindow) { typical_prompt_tokens = typical_prompt_tokens as u64, "serving geometry recorded — observed cache preference, not a future capacity constraint" ), - _ => continuum_base::probe!( + Err(error) => continuum_base::probe!( class = "serving.window.store_failed", path = %path.display(), + error = %error, "could not write the served-window store — the next boot re-derives the window" ), } @@ -202,7 +212,7 @@ fn write_record(path: &Path, stored: &StoredServedWindow) { mod tests { use super::*; use crate::inference::planning::serving_plan::{plan_serving_at_rest, HostBudget, ModelFootprint, ServingDemand}; - use crate::inference::planning::window_allocator::LaneRequirement; + use crate::inference::planning::window_allocator::{test_tokens, LaneRequirement}; #[test] fn observed_collapse_survives_restart_as_history_not_an_allocation_limit() { @@ -213,8 +223,8 @@ mod tests { let host = HostBudget { usable_bytes: 30 << 30, perf_cores: 8 }; let initial = plan_serving_at_rest(&host, std::slice::from_ref(&model), None, &ServingDemand::new(2, Some(70_000)).with_requirements(vec![ - LaneRequirement::declared(uuid::Uuid::new_v4(), 70_000), - LaneRequirement::declared(uuid::Uuid::new_v4(), 70_000)])).unwrap(); + LaneRequirement::declared(uuid::Uuid::new_v4(), test_tokens(70_000)), + LaneRequirement::declared(uuid::Uuid::new_v4(), test_tokens(70_000))])).unwrap(); let large = ServedGeometry { model_id: model.model_id.clone(), generation: uuid::Uuid::new_v4(), per_slot_window: initial.served_context_window, lanes: initial.lanes }; record_reconciled_to(&path, large.clone(), false, Some(60_000)); @@ -247,8 +257,8 @@ mod tests { assert_eq!(restarted.observed_prompt_tokens, Some(2048)); // Both real allocation branches use the same current demand and already // credited budget for cold boot and settled reconciliation. - for requirements in [vec![], vec![LaneRequirement::declared(uuid::Uuid::new_v4(), 70_000), - LaneRequirement::declared(uuid::Uuid::new_v4(), 70_000)]] { + for requirements in [vec![], vec![LaneRequirement::declared(uuid::Uuid::new_v4(), test_tokens(70_000)), + LaneRequirement::declared(uuid::Uuid::new_v4(), test_tokens(70_000))]] { // Legacy callers express their current per-lane requirement through // the measured prompt median (56k plus existing headroom = 70k). // Without it they may legitimately choose two narrower lanes. @@ -261,7 +271,7 @@ mod tests { assert!(cold.served_context_window >= 70_000); assert_eq!((cold.lanes, cold.served_context_window), (settled.lanes, settled.served_context_window)); assert!(model.peak_resident_bytes(cold.served_context_window, cold.lanes) <= host.usable_bytes); - let tight = HostBudget { usable_bytes: model.peak_resident_bytes(cold.served_context_window, 1), ..host.clone() }; + let tight = HostBudget { usable_bytes: model.peak_resident_bytes(cold.served_context_window, 1), ..host }; let edge = plan_serving_at_rest(&tight, std::slice::from_ref(&model), None, &demand).unwrap(); assert_eq!(edge.lanes, 1); assert!(model.peak_resident_bytes(edge.served_context_window, edge.lanes) <= tight.usable_bytes); diff --git a/core/continuum-grid/src/grid_allocator.rs b/core/continuum-grid/src/grid_allocator.rs index 7ea64e2dc6..b477d1ba81 100644 --- a/core/continuum-grid/src/grid_allocator.rs +++ b/core/continuum-grid/src/grid_allocator.rs @@ -182,7 +182,7 @@ pub fn minds_over_the_grid( // not exiled (card 70706a9e). requirements .iter() - .filter_map(|r| r.window.map(|w| (r.persona, r.need.map_or(w, |n| n.min(w))))) + .filter_map(|r| Some((r.persona, r.measure.need()?.get()))) .filter(|(_, w)| *w > widest_window) .collect() } @@ -283,7 +283,16 @@ pub fn dormant_by_age(dormant: &[Uuid], now_ms: u64, boot_ms: u64, last_turn_ms: /// (`free_slots_live / lanes` — the seat's own admission truth, so a lane a leased-in /// generate is using counts less than an empty one). pub fn slack_seats(open: &[OpenSeats], idle_fraction_of: impl Fn(Uuid) -> f64) -> f64 { - open.iter().map(|o| o.count as f64 * idle_fraction_of(o.node).clamp(0.0, 1.0)).sum() + open.iter().map(|o| o.count as f64 * idle_fraction_of(o.node)).sum() +} + +/// The share of a node's lanes free now, in [0, 1] by construction: a free count past the lanes (a +/// report racing a relaunch) counts as every lane free, never more; no lanes is no idle seat. +pub fn idle_fraction(free_slots: u64, lanes: u64) -> f64 { + match lanes { + 0 => 0.0, + lanes => free_slots.min(lanes) as f64 / lanes as f64, + } } /// How often the slack can give each dormant mind a turn: the typical turn, times the @@ -458,13 +467,13 @@ impl Inner { let dormant = dormant_by_age(&allocation.dormant, facts.now_ms, boot, crate::cognition::turn_ledger::last_turn_ms); let idle_of = |node: Uuid| -> f64 { if node == facts.this_node { - return if facts.local_lanes > 0 { facts.local_free_slots as f64 / facts.local_lanes as f64 } else { 0.0 }; + return idle_fraction(facts.local_free_slots as u64, facts.local_lanes as u64); } facts .peers .iter() .find(|p| p.node == node) - .map(|p| if p.lanes > 0 { p.free_slots_live as f64 / p.lanes as f64 } else { 0.0 }) + .map(|p| idle_fraction(p.free_slots_live as u64, p.lanes as u64)) .unwrap_or(0.0) // unwrap_or: a node the facts do not name has no idle seat to lend }; let slack = slack_seats(&allocation.open, idle_of); @@ -483,7 +492,7 @@ impl Inner { .allocation .nodes .iter() - .map(|n| format!("{}:{}", &n.node.to_string()[..8], n.seats)) + .map(|n| format!("{}:{}", airc_core::shown_id::shown_form(n.node), n.seats)) .collect(); continuum_base::probe!( class = "grid.allocation.published", @@ -536,11 +545,11 @@ impl Inner { // turn is known and the target did (card 70706a9e) — the reader must // never again mistake a pre-fit wish for a lane width. .map(|(m, w)| { - let gate = match requirements.iter().find(|r| r.persona == *m).and_then(|r| r.need) { - Some(_) => "need", - None => "wish", + let gate = match requirements.iter().find(|r| r.persona == *m).map(|r| r.measure) { + Some(crate::inference::planning::window_allocator::Measure::Held { .. }) => "need", + _ => "wish", }; - format!("{}:{gate}:{w}", m.to_string().chars().take(8).collect::()) + format!("{}:{gate}:{w}", airc_core::shown_id::shown_form(*m)) }) .collect::>() .join(","), @@ -893,15 +902,21 @@ mod tests { // sentence. Aiko at ~24k fits and must never be named. #[test] fn a_mind_whose_turn_exceeds_every_lane_is_named_and_the_ones_that_fit_are_not() { - use crate::inference::planning::window_allocator::LaneRequirement; + use crate::inference::planning::window_allocator::{LaneRequirement, Tokens}; + const fn t(n: u32) -> Tokens { + match Tokens::new(n) { + Some(tokens) => tokens, + None => panic!("a test's token literal is never zero"), + } + } let benchy = Uuid::new_v4(); let aiko = Uuid::new_v4(); let unmeasured = Uuid::new_v4(); let reqs = vec![ - LaneRequirement::from_demand(benchy, 110_396, 1.0), - LaneRequirement::from_demand(aiko, 24_226, 1.0), + LaneRequirement::wished(benchy, t(110_396), 1.0), + LaneRequirement::wished(aiko, t(24_226), 1.0), // no turn yet: Unknown, and an absence is never a number - LaneRequirement::from_demand(unmeasured, 0, 1.0), + LaneRequirement::unmeasured(unmeasured), ]; let named = minds_over_the_grid(&reqs, 78_592); @@ -923,13 +938,13 @@ mod tests { // she is still named — the need gates in both directions. A need above the // target is clamped to the target (a floor cannot exceed what it floors). let kimi = Uuid::new_v4(); - let wish = vec![LaneRequirement::from_demand(kimi, 99_096, 1.25)]; + let wish = vec![LaneRequirement::wished(kimi, t(99_096), 1.25)]; assert_eq!(minds_over_the_grid(&wish, 75_776), vec![(kimi, 123_870)], "no need known: the wish gates, as before"); - let fits = vec![LaneRequirement::from_demand(kimi, 99_096, 1.25).with_need(74_000)]; + let fits = vec![LaneRequirement::wished(kimi, t(99_096), 1.25).held(t(74_000))]; assert!(minds_over_the_grid(&fits, 75_776).is_empty(), "her held turns fit this grid: served, trimmed, not exiled"); - let over = vec![LaneRequirement::from_demand(kimi, 99_096, 1.25).with_need(80_000)]; + let over = vec![LaneRequirement::wished(kimi, t(99_096), 1.25).held(t(80_000))]; assert_eq!(minds_over_the_grid(&over, 75_776), vec![(kimi, 80_000)], "a need the grid cannot hold still names her, by the need"); - let clamped = vec![LaneRequirement::from_demand(kimi, 60_000, 1.0).with_need(90_000)]; + let clamped = vec![LaneRequirement::wished(kimi, t(60_000), 1.0).held(t(90_000))]; assert!(minds_over_the_grid(&clamped, 60_000).is_empty(), "need clamps to the target"); } } diff --git a/core/continuum-serving/src/modules/serving_daemon/grants.rs b/core/continuum-serving/src/modules/serving_daemon/grants.rs index 18b40b636d..9e8fb163ef 100644 --- a/core/continuum-serving/src/modules/serving_daemon/grants.rs +++ b/core/continuum-serving/src/modules/serving_daemon/grants.rs @@ -26,8 +26,7 @@ impl ServingDaemonModule { minds = grants.by_mind.len() as u64, granted = grants.by_mind.values().map(|g| u64::from(*g)).sum::(), grants = ?grants.by_mind, - from_population = ?grants.from_population, - "each local mind's window on the engine's pool: her measured requirement, granted by demand-following" + "each measured local mind's window on the engine's pool: her need, her target when every target fits" ); } } @@ -50,41 +49,31 @@ impl ServingDaemonModule { .active_model .as_deref() .and_then(|id| (self.model_resolver)(id)) - .map(|model| model.context_window)?; + .and_then(|model| crate::inference::planning::window_allocator::Tokens::new(model.context_window))?; let per_sequence_cap = match self.on_shared_pool()? { - true => pool_tokens.min(trained), + true => pool_tokens.min(trained.get()), false => live.served_context_window, }; - let requirements = self.serving_demand().requirements; - // A mind not measured yet claims the population's measured requirement on this seat, - // marked as such (ONE-BUDGET: an unmeasured claim never asks for the most). With no one - // measured she is granted nothing yet and keeps her binding until her first turn is. - let population = population_requirement(requirements.iter().map(|r| r.window)); - let mut from_population = std::collections::BTreeSet::new(); - let demands: Vec> = requirements + // Only a measured mind has a demand: an unmeasured one has no number to grant (her first view + // measures her), never the population's or anyone else's. The model's trained window is the one + // hard limit on both her floor and her target (her context compresses to it). + let demands: Vec> = self + .serving_demand() + .requirements .iter() .filter_map(|r| { - let required = match r.window { - Some(own) => own, - None => { - from_population.insert(r.persona); - population? - } - }; Some(Demand { mind: r.persona, - // The model's trained window is the one hard limit (her context compresses to it); - // a need above what the pool holds now is not trimmed here, it waits. - required_tokens: required.min(trained), + need: r.measure.need()?.min(trained), + target: r.measure.target()?.min(trained), in_flight: crate::cognition::turn_ledger::turn_in_flight(r.persona), ceiling: per_sequence_cap, }) }) .collect(); - from_population.retain(|mind| demands.iter().any(|d| d.mind == *mind)); let held = self.grants_tx.borrow().as_ref().map(|g| g.by_mind.clone()).unwrap_or_default(); // unwrap_or_default: nothing granted yet holds nothing let by_mind = DemandFollowing.grant(&demands, &held, pool_tokens); - Some(PoolGrants { pool_tokens, per_sequence_cap, by_mind, from_population }) + Some(PoolGrants { pool_tokens, per_sequence_cap, by_mind }) } /// Whether the running engine is on the shared pool, read off its argv once per process. @@ -100,25 +89,3 @@ impl ServingDaemonModule { Some(shared) } } - -/// The population's measured requirement on this seat: the median of the minds measured so far. -/// `None` when no one is. -fn population_requirement(windows: impl Iterator>) -> Option { - let mut measured: Vec = windows.flatten().collect(); - measured.sort_unstable(); - measured.get(measured.len() / 2).copied() -} - -#[cfg(test)] -mod tests { - use super::population_requirement; - - // what this catches: the least-known mind claiming the biggest share (Cormac on #5733: an - // unmeasured mind asked for the largest requirement on the seat, or the whole cap). She claims - // the population's median, and nothing when no one is measured. - #[test] - fn an_unmeasured_mind_claims_the_median_never_the_most() { - assert_eq!(population_requirement([Some(70_000), None, Some(10_000), Some(20_000)].into_iter()), Some(20_000)); - assert_eq!(population_requirement([None, None].into_iter()), None); - } -} diff --git a/core/continuum-serving/src/modules/serving_daemon/planning.rs b/core/continuum-serving/src/modules/serving_daemon/planning.rs index 16fe2f5aa7..b661e28775 100644 --- a/core/continuum-serving/src/modules/serving_daemon/planning.rs +++ b/core/continuum-serving/src/modules/serving_daemon/planning.rs @@ -709,7 +709,7 @@ fn plan_decisions( #[cfg(test)] mod training_lease_tests { use super::*; - use crate::inference::planning::window_allocator::{allocate, LaneRequirement, TrainingGrowth, TrainingPrice, TrainingReserve}; + use crate::inference::planning::window_allocator::{allocate, test_tokens, LaneRequirement, TrainingGrowth, TrainingPrice, TrainingReserve}; use crate::resources::lease::{ReclaimPolicy, ResourceLease}; // What this catches: unrelated or different-job leases cannot cancel a @@ -722,7 +722,7 @@ mod training_lease_tests { source: crate::inference::planning::training_plan::NeedSource::LowerBound, model: "fixture".into(), shape: "fixture".into(), }; - let requirement = LaneRequirement::declared(uuid::Uuid::from_u128(1), 40_000) + let requirement = LaneRequirement::declared(uuid::Uuid::from_u128(1), test_tokens(40_000)) .with_training(Some(TrainingReserve::new(64_256, Some(price), Some(job)))); let mut demand = ServingDemand::new(1, Some(40_000)).with_requirements(vec![requirement]); let lease = |id: &str, consumer: String, bytes| ResourceLease {