diff --git a/core/continuum-cognition/src/cognition/persona_workspace/rehome.rs b/core/continuum-cognition/src/cognition/persona_workspace/rehome.rs index 68ab95e9a4..8b340b0903 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/rehome.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/rehome.rs @@ -1,5 +1,6 @@ //! Serving-edge model binding updates for registered residents: every LOCAL resident is -//! bound to exactly what serving reports (model AND window), corrected per persona. +//! bound to exactly what serving reports: its model, and HER window (her grant on the engine's +//! pool, never one window for everyone), corrected per persona. use super::PersonaWorkspaceRegistry; use crate::ai::adapter::AIProviderAdapter; use crate::cognition::llm_deliberation_faculty::ModelBinding; @@ -64,7 +65,7 @@ impl PersonaWorkspaceRegistry { .collect() } - /// What the served `(model, context_window)` asks of the local residents: `None` when + /// What the served model and each resident's own window (`window_of`) ask of the local residents: `None` when /// every one is already bound to it (the steady-state tick is free), /// `Some(ModelChanged)` when any needs the new model (the caller builds ONE shared /// adapter), else `Some(WindowChanged)` (each keeps her adapter). @@ -72,24 +73,24 @@ impl PersonaWorkspaceRegistry { &self, root: &std::path::Path, model: &str, - context_window: u32, + window_of: impl Fn(Uuid) -> Option, ) -> Option { let assignments = self.assignments_at(root); let cycles = self.cycles.lock(); cycles .iter() .filter(|(id, _)| matches!(assignments.get(*id), Some(Assignment::Local))) - .filter_map(|(_, entry)| entry.cycle.current_binding()) - .filter_map(|binding| RehomeReason::of(&binding, model, context_window)) + .filter_map(|(id, entry)| Some((entry.cycle.current_binding()?, window_of(*id)?))) + .filter_map(|(binding, window)| RehomeReason::of(&binding, model, window)) .max_by_key(|reason| *reason == RehomeReason::ModelChanged) } /// [`rehome_reason_at`](Self::rehome_reason_at) under this process's continuum root. - pub fn rehome_reason(&self, model: &str, context_window: u32) -> Option { - self.rehome_reason_at(&crate::paths::continuum_root(), model, context_window) + pub fn rehome_reason(&self, model: &str, window_of: impl Fn(Uuid) -> Option) -> Option { + self.rehome_reason_at(&crate::paths::continuum_root(), model, window_of) } - /// Bind EVERY local resident to the served `(model, context_window)` — atomically + /// Bind EVERY local resident to the served model and her own window (`window_of`) — atomically /// swapping the shared {adapter, model, context_window} binding on each cycle (see /// [`crate::cognition::workspace::WorkspaceCycle::rebind_model`]). A resident already /// bound to it is untouched. A model change rebinds through the ONE shared `adapter` @@ -104,7 +105,7 @@ impl PersonaWorkspaceRegistry { root: &std::path::Path, adapter: Option>, model: &str, - context_window: u32, + window_of: impl Fn(Uuid) -> Option, ) -> usize { let assignments = self.assignments_at(root); let cycles = self.cycles.lock(); @@ -128,6 +129,15 @@ impl PersonaWorkspaceRegistry { let Some(current) = entry.cycle.current_binding() else { continue; // no deliberation faculty shared a binding in: nothing to rebind. }; + let Some(context_window) = window_of(*id) else { + continuum_base::probe!( + class = "persona.rehome.kept_binding", + persona_id = %id, + reason = "no_grant", + "re-home skipped: serving has granted her no window on the engine's pool yet" + ); + continue; + }; let Some(reason) = RehomeReason::of(¤t, model, context_window) else { continue; }; @@ -169,13 +179,8 @@ impl PersonaWorkspaceRegistry { &self, adapter: Option>, model: &str, - context_window: u32, + window_of: impl Fn(Uuid) -> Option, ) -> usize { - self.re_home_all_at( - &crate::paths::continuum_root(), - adapter, - model, - context_window, - ) + self.re_home_all_at(&crate::paths::continuum_root(), adapter, model, window_of) } } diff --git a/core/continuum-core/src/ipc/start_server/rehome_reconciler.rs b/core/continuum-core/src/ipc/start_server/rehome_reconciler.rs index 54acc50cc6..9f985c6395 100644 --- a/core/continuum-core/src/ipc/start_server/rehome_reconciler.rs +++ b/core/continuum-core/src/ipc/start_server/rehome_reconciler.rs @@ -3,9 +3,11 @@ use super::*; // ── Served-model re-home reconciler ───────────────────────────────────── -// The base-model sibling of LoRA/genome paging. The serving snapshot is the ONE -// owner of "the binding a local persona deliberates through": its active model -// AND its served context window. This task owns the serving-SNAPSHOT watch and, +// The base-model sibling of LoRA/genome paging. Serving is the ONE owner of "the +// binding a local persona deliberates through": the snapshot's active model, and her +// OWN window, the grant serving gives her on the engine's pool from her measured +// requirement (`serving_daemon/grants.rs`). One window for everyone was the division +// Joel ruled out on 2026-11-03 ("What a mind needs not what you dictate"). This task owns the serving-SNAPSHOT watch and, // on every ready snapshot, binds every local resident to exactly that pair — // WITHOUT losing the genome, working memory, or admission she accumulated. That // covers a `serving/pin`, a re-plan under memory pressure, a grid failover, AND a @@ -29,6 +31,7 @@ pub(super) fn spawn_rehome_reconciler( serving_daemon: &Arc, ) { let mut serving_rx = serving_daemon.subscribe_serving(); + let mut grants_rx = serving_daemon.subscribe_grants(); rt_handle.spawn(async move { // LEVEL-TRIGGERED retry (#368): edge-only waking is how 4 citizens // stayed stranded on a torn-down model for 47 minutes — the adapter @@ -50,6 +53,12 @@ pub(super) fn spawn_rehome_reconciler( break; } } + changed = grants_rx.changed() => { + if changed.is_err() { + tracing::info!("serving-grants watch closed — re-home reconciler exiting (substrate shutdown)"); + break; + } + } _ = retry.tick() => {} } let snap = serving_rx.borrow_and_update().clone(); @@ -59,10 +68,13 @@ pub(super) fn spawn_rehome_reconciler( let Some(active) = snap.active_model.clone() else { continue; }; - let window = snap.served_context_window; + let Some(grants) = grants_rx.borrow_and_update().clone() else { + continue; // serving has granted no window yet: nobody's binding moves on a guess. + }; + let window_of = |persona: uuid::Uuid| grants.grant_for(persona); let workspaces = crate::cognition::persona_workspace::global(); - let Some(reason) = workspaces.rehome_reason(&active, window) else { - continue; // every local resident is already bound to (model, window). + let Some(reason) = workspaces.rehome_reason(&active, window_of) else { + continue; // every local resident is already bound to the model and her grant. }; // A new model needs the ONE shared served-model adapter. Fail LOUD into // a log — a failed build leaves residents on their prior (still-live) @@ -85,13 +97,13 @@ pub(super) fn spawn_rehome_reconciler( } } }; - let n = workspaces.re_home_all(adapter, &active, window); + let n = workspaces.re_home_all(adapter, &active, window_of); tracing::info!( model = %active, - context_window = window, + pool_tokens = grants.pool_tokens, personas = n, ?reason, - "re-homed local residents onto the served binding" + "re-homed local residents onto the served model and each one's grant" ); } }); diff --git a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs index 294c48a5a4..18b78567e2 100644 --- a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs +++ b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs @@ -68,13 +68,13 @@ async fn rehome_requires_a_readable_local_assignment() { let replacement: Arc = Arc::new(HeuristicInferenceAdapter::new()); for corrupt in [false, true] { if corrupt { std::fs::write(home.model_override_json(), b"{").expect("corrupt"); } - assert_eq!(registry.re_home_all_at(root.path(), Some(replacement.clone()), "new/local", 4096), 0); + assert_eq!(registry.re_home_all_at(root.path(), Some(replacement.clone()), "new/local", |_| Some(4096)), 0); let (actual, model) = cycle.current_model_route().expect("preserved"); assert!(Arc::ptr_eq(&original, &actual)); assert_eq!(model, original_model); } PersonaModelOverride::new("local/model", None, 2).write(&home).expect("local override"); - assert_eq!(registry.re_home_all_at(root.path(), Some(replacement.clone()), "new/local", 4096), 1); + assert_eq!(registry.re_home_all_at(root.path(), Some(replacement.clone()), "new/local", |_| Some(4096)), 1); let (actual, model) = cycle.current_model_route().expect("rebound"); assert!(Arc::ptr_eq(&replacement, &actual)); assert_eq!(model.as_deref(), Some("new/local")); @@ -104,8 +104,8 @@ async fn a_resident_bound_at_the_provisional_window_is_rehomed_to_the_served_win assert_eq!(before.context_window, crate::inference::planning::MIN_SERVE_CTX, "bound at the provisional window"); let served = 60_672; - assert_eq!(registry.rehome_reason_at(root.path(), &model, served), Some(RehomeReason::WindowChanged)); - assert_eq!(registry.re_home_all_at(root.path(), None, &model, served), 1, "only the local resident moves"); + assert_eq!(registry.rehome_reason_at(root.path(), &model, |_| Some(served)), Some(RehomeReason::WindowChanged)); + assert_eq!(registry.re_home_all_at(root.path(), None, &model, |_| Some(served)), 1, "only the local resident moves"); let after = local.current_binding().expect("rebound"); assert_eq!(after.context_window, served); assert_eq!(after.requested_model(), model); @@ -113,8 +113,8 @@ async fn a_resident_bound_at_the_provisional_window_is_rehomed_to_the_served_win let remote_after = remote.current_binding().expect("remote kept"); assert!(Arc::ptr_eq(&remote_before, &remote_after), "the off-box resident keeps her binding"); - assert_eq!(registry.rehome_reason_at(root.path(), &model, served), None, "steady state needs nothing"); - assert_eq!(registry.re_home_all_at(root.path(), None, &model, served), 0, "already bound: untouched"); + assert_eq!(registry.rehome_reason_at(root.path(), &model, |_| Some(served)), None, "steady state needs nothing"); + assert_eq!(registry.re_home_all_at(root.path(), None, &model, |_| Some(served)), 0, "already bound: untouched"); assert!(Arc::ptr_eq(&after, &local.current_binding().expect("still bound")), "no store on a matching binding"); } diff --git a/core/continuum-engine/src/capacity/mod.rs b/core/continuum-engine/src/capacity/mod.rs index 6bfb7b17e3..be8982ab0e 100644 --- a/core/continuum-engine/src/capacity/mod.rs +++ b/core/continuum-engine/src/capacity/mod.rs @@ -56,6 +56,7 @@ pub mod score; pub mod serving_pager; pub mod settlement; pub mod sim; +pub mod window_grant; pub mod window_sim; pub mod system_profile; #[cfg(any(test, feature = "test-fixtures"))] diff --git a/core/continuum-engine/src/capacity/window_grant.rs b/core/continuum-engine/src/capacity/window_grant.rs new file mode 100644 index 0000000000..eb73f13979 --- /dev/null +++ b/core/continuum-engine/src/capacity/window_grant.rs @@ -0,0 +1,146 @@ +//! A mind's window in the shared pool is what she needs, granted from her measured requirement; +//! never the pool divided by a count (Joel, 2026-11-03: "It's all about what they need. System +//! accommodates it doesn't do stupid division"; "Stupid divisions or constants are always gonna +//! fail"). +//! +//! [`DemandFollowing`] grants every mind her required tokens when the pool holds them all, and no +//! more: what is left stays unallocated in the shared pool, where any sequence may grow into it and +//! a mind whose need rises is granted it on the next tick. A slack share granted as a window would +//! be pinned by a turn in flight while another mind's real need went unmet (Cormac on #5733). When +//! the pool cannot hold every need, a turn in flight keeps at least what it holds (a grant never shrinks under a running +//! turn) and the rest share what remains in proportion to what each still needs, so every prompt +//! compresses to its grant instead of one mind being cut while another holds slack. The pool is +//! the engine's; paging a cold mind out and making the next one wait for admission are how the +//! node accommodates past it. [`super::window_sim`] validates the contract against today's equal +//! split; ONE-BUDGET slice 3b's solver replaces this policy with `cambrian-flex` claims. + +use std::collections::BTreeMap; + +/// 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)] +pub struct PoolGrants { + /// The engine's pool: every token its KV holds. + pub pool_tokens: u32, + /// The most one sequence may hold: the pool itself on a shared pool (capped at the trained + /// 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 { + /// Her grant, when she is one of the minds on this pool. + pub fn grant_for(&self, persona: uuid::Uuid) -> Option { + self.by_mind.get(&persona).copied() + } +} + +/// One mind's current demand on the pool: what her next turn requires, and whether a turn of hers +/// is in flight now. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Demand { + pub mind: K, + pub required_tokens: u32, + pub in_flight: bool, + /// The most she may be granted: what one sequence of the engine can hold. + pub ceiling: u32, +} + +/// Grants every mind a window from the pool, given every mind's current demand and the grants +/// they hold now. +pub trait WindowPolicy { + fn grant(&mut self, demands: &[Demand], held: &BTreeMap, pool_tokens: u32) -> BTreeMap; +} + +/// Demand-following over one shared pool: every mind is granted her demand, up to her ceiling, +/// when the pool holds them all; otherwise in-flight grants are kept whole and the rest share what +/// remains in proportion to their demand. Nothing beyond a demand is granted. +pub struct DemandFollowing; + +impl WindowPolicy for DemandFollowing { + fn grant( + &mut self, + demands: &[Demand], + held: &BTreeMap, + pool_tokens: u32, + ) -> BTreeMap { + // A turn in flight keeps at least what it holds: its grant is a floor whether or not + // every demand fits (Cormac on #5718: the fits branch granted the new, smaller demand + // and shrank a turn mid-flight). The floors fit the pool because they were granted + // inside it; what they leave is shared over the rest of each mind's demand, whole when + // it all fits and in proportion when it does not. + let floor = |d: &Demand| match d.in_flight { + true => held.get(&d.mind).copied().unwrap_or(0), // unwrap_or: a turn that holds nothing yet has no floor + false => 0, + }; + let floors: u64 = demands.iter().map(|d| u64::from(floor(d))).sum(); + let rest = u64::from(pool_tokens).saturating_sub(floors); + let needed: u64 = demands + .iter() + .map(|d| u64::from(d.required_tokens.saturating_sub(floor(d)))) + .sum(); + demands + .iter() + .map(|d| { + let need = u64::from(d.required_tokens.saturating_sub(floor(d))); + let more = match needed <= rest { + true => need, + false => (need * rest).checked_div(needed).unwrap_or(0), // unwrap_or: nothing needed means nothing more + }; + let granted = u64::from(floor(d)).saturating_add(more).min(u64::from(d.ceiling.max(floor(d)))); + (d.mind, u32::try_from(granted).unwrap_or(u32::MAX)) // unwrap_or: a grant is at most her ceiling, a u32 + }) + .collect() + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + fn demand(mind: u32, required_tokens: u32, in_flight: bool, ceiling: u32) -> Demand { + Demand { mind, required_tokens, in_flight, ceiling } + } + + // what this catches: a window divided by a count (Joel, 2026-11-03: "What a mind needs not what + // you dictate"). Minds that fit get exactly what they need, never an equal split, never past one + // sequence's ceiling; what is left stays in the pool, granted to no one. + #[test] + fn every_mind_gets_what_she_needs_and_the_rest_stays_in_the_pool() { + let pool = 257_536; + let demands = [demand(1, 70_000, false, pool), demand(2, 20_000, false, pool), demand(3, 10_000, false, pool)]; + let grants = DemandFollowing.grant(&demands, &BTreeMap::new(), pool); + assert_eq!(grants, BTreeMap::from([(1, 70_000), (2, 20_000), (3, 10_000)])); + let capped = DemandFollowing.grant(&[demand(1, 40_000, false, 32_768)], &BTreeMap::new(), pool); + assert_eq!(capped[&1], 32_768, "no grant past what one sequence can hold"); + } + + // what this catches: slack granted as windows and then pinned by a turn in flight while another + // mind's real need goes unmet (Cormac on #5733: pool 65,536, A and B each granted 32,768 for a + // 10,000 need; A in flight; B rose to 40,000 and got 32,768 while A held 22,768 unused). + #[test] + fn a_running_turn_pins_only_what_it_needed_and_a_rising_need_is_met() { + let pool = 65_536; + let first = DemandFollowing.grant(&[demand(1, 10_000, false, pool), demand(2, 10_000, false, pool)], &BTreeMap::new(), pool); + assert_eq!(first, BTreeMap::from([(1, 10_000), (2, 10_000)])); + let next = DemandFollowing.grant(&[demand(1, 10_000, true, pool), demand(2, 40_000, false, pool)], &first, pool); + assert_eq!(next, BTreeMap::from([(1, 10_000), (2, 40_000)]), "B's need is met beside A's running turn"); + } + + // what this catches: needs past the pool cutting a running turn, or anyone's grant decided by a + // count. A turn in flight keeps what it holds; the others share the rest in proportion to need. + #[test] + fn past_the_pool_a_running_turn_keeps_its_grant_and_the_rest_share_by_need() { + let pool = 65_536; + let held = BTreeMap::from([(1, 30_000)]); + let demands = [demand(1, 20_000, true, pool), demand(2, 40_000, false, pool), demand(3, 20_000, false, pool)]; + let grants = DemandFollowing.grant(&demands, &held, pool); + assert_eq!(grants[&1], 30_000, "a running turn's grant never shrinks under it"); + assert!(grants.values().map(|&g| u64::from(g)).sum::() <= u64::from(pool)); + assert_eq!(grants[&2], 2 * grants[&3], "the rest share by need: {grants:?}"); + } +} diff --git a/core/continuum-engine/src/capacity/window_sim.rs b/core/continuum-engine/src/capacity/window_sim.rs index 7ae609d632..269e5e81e4 100644 --- a/core/continuum-engine/src/capacity/window_sim.rs +++ b/core/continuum-engine/src/capacity/window_sim.rs @@ -38,24 +38,9 @@ pub struct WindowScenario { pub events: Vec, } -/// The current demand of every mind on the pool, as a policy reads it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Demand { - pub mind: MindId, - pub required_tokens: u32, - pub in_flight: bool, -} - -/// Grants every mind a window from the pool, given every mind's current demand and the grants -/// they hold now. -pub trait WindowPolicy { - fn grant( - &mut self, - demands: &[Demand], - held: &BTreeMap, - pool_tokens: u32, - ) -> BTreeMap; -} +/// The production grant types, keyed by the simulator's small mind ids. +pub use super::window_grant::{DemandFollowing, WindowPolicy}; +pub type Demand = super::window_grant::Demand; /// What a run measured, and every contract breach it saw. #[derive(Debug, Default, Clone, PartialEq, Eq)] @@ -74,7 +59,7 @@ impl WindowRun { } /// Play `scenario` through `policy`, one regrant per demand event. -pub fn run(scenario: &WindowScenario, policy: &mut dyn WindowPolicy) -> WindowRun { +pub fn run(scenario: &WindowScenario, policy: &mut dyn WindowPolicy) -> WindowRun { let mut demands: BTreeMap = BTreeMap::new(); let mut held: BTreeMap = BTreeMap::new(); let mut out = WindowRun::default(); @@ -85,6 +70,8 @@ pub fn run(scenario: &WindowScenario, policy: &mut dyn WindowPolicy) -> WindowRu mind: event.mind, required_tokens: event.required_tokens, in_flight: event.in_flight, + // the shared pool: one sequence may hold all of it + ceiling: scenario.pool_tokens, }, ); let current: Vec = demands.values().copied().collect(); @@ -142,7 +129,7 @@ pub struct EqualSplit { pub slots: u32, } -impl WindowPolicy for EqualSplit { +impl WindowPolicy for EqualSplit { fn grant( &mut self, demands: &[Demand], @@ -154,48 +141,6 @@ impl WindowPolicy for EqualSplit { } } -/// Demand-following over one shared pool: every mind is granted her demand when the pool holds -/// them all; otherwise in-flight grants are kept whole and the rest share what remains in -/// proportion to their demand. -pub struct DemandFollowing; - -impl WindowPolicy for DemandFollowing { - fn grant( - &mut self, - demands: &[Demand], - held: &BTreeMap, - pool_tokens: u32, - ) -> BTreeMap { - // A turn in flight keeps at least what it holds: its grant is a floor whether or not - // every demand fits (Cormac on #5718: the fits branch granted the new, smaller demand - // and shrank a turn mid-flight). The floors fit the pool because they were granted - // inside it; what they leave is shared over the rest of each mind's demand, whole when - // it all fits and in proportion when it does not. - let floor = |d: &Demand| match d.in_flight { - true => held.get(&d.mind).copied().unwrap_or(0), // unwrap_or: a turn that holds nothing yet has no floor - false => 0, - }; - let floors: u64 = demands.iter().map(|d| u64::from(floor(d))).sum(); - let rest = u64::from(pool_tokens).saturating_sub(floors); - let needed: u64 = demands - .iter() - .map(|d| u64::from(d.required_tokens.saturating_sub(floor(d)))) - .sum(); - demands - .iter() - .map(|d| { - let need = u64::from(d.required_tokens.saturating_sub(floor(d))); - let more = match needed <= rest { - true => need, - false => (need * rest).checked_div(needed).unwrap_or(0), // unwrap_or: nothing needed means nothing more - }; - let more = u32::try_from(more).unwrap_or(u32::MAX); // unwrap_or: more is at most her need, a u32 - (d.mind, floor(d).saturating_add(more)) - }) - .collect() - } -} - /// The M5 on 2026-11-02: 290,560 tokens of KV pool; Aiko reading large files (instantiate.rs /// and skeleton.rs, ~70k of view), Benchy and Aris mid-work, Atlas quiet, and scratch traffic /// (a 432-token prompt) beside them. diff --git a/core/continuum-serving/src/modules/serving_daemon.rs b/core/continuum-serving/src/modules/serving_daemon.rs index f41aecde90..cf6f59000d 100644 --- a/core/continuum-serving/src/modules/serving_daemon.rs +++ b/core/continuum-serving/src/modules/serving_daemon.rs @@ -351,6 +351,15 @@ pub struct ServingDaemonModule { /// The engine process this core last asked to move onto the shared pool: one try per /// engine, so a refused move is never retried every tick. shared_pool_move_tried: Arc, + /// Each local mind's grant on the engine's pool (`grants.rs`): what her binding follows. + /// `None` until a ready engine has been granted from. + grants_tx: watch::Sender>, + /// Whether the engine process `pid` runs on the shared pool: read off its argv once per + /// process, never every tick. + shared_pool_of: Arc>>, + /// The pool the running engine reports (`served_pool_tokens`, its `context_geometry`), as + /// the launch's ready path last read it; `0` = not read. The grants' one source for the pool. + served_pool: Arc, /// L10 (#438): consecutive plan ticks wanting a DIFFERENT base model than the /// ready incumbent, and which model that was. A model swap re-homes every @@ -541,6 +550,9 @@ impl ServingDaemonModule { lane_demand: Arc::new(std::sync::atomic::AtomicU32::new(1)), plan_budget_bytes: Arc::new(std::sync::atomic::AtomicU64::new(0)), shared_pool_move_tried: Arc::new(std::sync::atomic::AtomicU64::new(0)), + grants_tx: watch::channel(None).0, + shared_pool_of: Arc::new(parking_lot::Mutex::new(None)), + served_pool: Arc::new(std::sync::atomic::AtomicU32::new(0)), model_change_streak: Arc::new(std::sync::atomic::AtomicU32::new(0)), pending_model_change: Arc::new(std::sync::Mutex::new(None)), serving_hold: Arc::new(parking_lot::Mutex::new(None)), @@ -664,6 +676,7 @@ use launch_window::adopted_prompt_cache_mib; use launch_window::{sticky_served_window, wedge_heal_floor}; mod launch; mod planning; +mod grants; mod hold; mod reconcile; mod tick; diff --git a/core/continuum-serving/src/modules/serving_daemon/grants.rs b/core/continuum-serving/src/modules/serving_daemon/grants.rs new file mode 100644 index 0000000000..72749c16bf --- /dev/null +++ b/core/continuum-serving/src/modules/serving_daemon/grants.rs @@ -0,0 +1,122 @@ +//! Each local mind's window on the engine's pool is her grant: her measured requirement +//! (`requirements_for`: the untrimmed demand her turns assemble, with headroom; the population's, +//! marked, until hers is measured), granted by +//! demand-following (`capacity::window_grant`). Never the pool divided by a count (Joel, +//! 2026-11-03: "System accommodates it doesn't do stupid division"). Published on every tick +//! that moves a grant; the re-home reconciler binds each mind to hers. +use super::*; +use crate::capacity::window_grant::{Demand, DemandFollowing, PoolGrants, WindowPolicy}; + +impl ServingDaemonModule { + /// The minds' grants on the running engine, published when one moves. + pub(super) fn publish_grants(&self) { + let next = self.grants_now(); + let changed = self.grants_tx.send_if_modified(|current| { + if *current == next { + return false; + } + current.clone_from(&next); + true + }); + if let (true, Some(grants)) = (changed, next.as_ref()) { + continuum_base::probe!( + target: "continuum_core::modules::serving_daemon", class = "serving.grants", + pool_tokens = grants.pool_tokens, + per_sequence_cap = grants.per_sequence_cap, + 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" + ); + } + } + + /// Subscribe to the minds' grants. + pub fn subscribe_grants(&self) -> watch::Receiver> { + self.grants_tx.subscribe() + } + + /// `None` until the engine serves and has reported its pool: there is nothing to grant from. + fn grants_now(&self) -> Option { + let live = self.serving_tx.borrow().clone(); + // The pool the engine itself reports (`context_geometry.allocated_tokens`), never a + // published share multiplied back by a count (Cormac on #5733). + let pool_tokens = self.served_pool.load(Ordering::Relaxed); + if !live.ready || live.served_context_window == 0 || pool_tokens == 0 { + return None; + } + let trained = live + .active_model + .as_deref() + .and_then(|id| (self.model_resolver)(id)) + .map(|model| model.context_window)?; + let per_sequence_cap = match self.on_shared_pool()? { + true => pool_tokens.min(trained), + 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 + .iter() + .filter_map(|r| { + let required = match r.window { + Some(own) => own, + None => { + from_population.insert(r.persona); + population? + } + }; + Some(Demand { + mind: r.persona, + required_tokens: required.min(per_sequence_cap), + 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 }) + } + + /// Whether the running engine is on the shared pool, read off its argv once per process. + fn on_shared_pool(&self) -> Option { + let pid = crate::inference::lane_pidfile::read()?; + if let Some((known, shared)) = *self.shared_pool_of.lock() { + if known == pid { + return Some(shared); + } + } + let shared = self.server.launched_on_shared_pool()?; + *self.shared_pool_of.lock() = Some((pid, shared)); + 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/launch.rs b/core/continuum-serving/src/modules/serving_daemon/launch.rs index 308f2731bc..37c3877320 100644 --- a/core/continuum-serving/src/modules/serving_daemon/launch.rs +++ b/core/continuum-serving/src/modules/serving_daemon/launch.rs @@ -19,26 +19,28 @@ impl ServingDaemonModule { /// The engine's one KV pool, sized ONCE when the engine starts and never by a relaunch, as /// `(per-sequence tokens, sequences)` so `-c` is the pool and `--parallel` the ceiling. /// - /// The sequences: every seated mind, the minds leased in at the last plan, and the scratch - /// traffic beside them. Each is laid out on the budget the last plan sized against, by the - /// plan's own arithmetic, so the engine holds the memory the planner proved it may: on the - /// M5, 5 x 69,376, the geometry the planner gave the fixed-slot engine. Sizing it instead - /// from the physical budget less every board holder gave 5 x 36,505 (2026-11-03 04:23Z, - /// backed out at once), and from the cold plan's window x lanes 1 x 80k. The shared pool's - /// saving (one compute graph, not one per sequence) comes as a measured gain, not here. A - /// model with no measured footprint, or no plan yet, keeps the plan's total (window x lanes) - /// shared over the sequences: an unmeasured model is where over-allocating is least safe. + /// The launch decides only the pool's size; no mind's window comes from it. Each mind's + /// window is her grant from her measured requirement (`grants.rs`), and under `--kv-unified` + /// any one sequence may grow into the whole pool. The pool is the most memory the plan's own + /// arithmetic proves fits: its window x its lanes, or its fit at the sequences (a window + /// within the budget for each), whichever is larger. The sequences are every seated mind, + /// the minds leased in at the last plan, and the scratch traffic, so seating never relaunches. + /// On the M5 (plan 2 x 128,768) that is 257,536 for 5; on the IntelMac (plan 2 x 32,768, + /// fit 9 x 32,768) 294,912 for 9, what it serves healthy today. Dividing the pool by the + /// sequences as each mind's window gave the M5 5 x 10,803 (b03d7c5bc) and would have given + /// the IntelMac 7,281 against 13-30k acts (Joel, 2026-11-03: "System accommodates it doesn't + /// do stupid division"). fn engine_pool(&self, model: &crate::model_registry::types::Model, served_ctx: u32, lanes: u32) -> (u32, u32) { let leased_in = LAST_LEASED_IN_PEAK.load(Ordering::Relaxed); - let sequences = self.seated().saturating_add(1).saturating_add(leased_in).max(lanes); + let sequences = self.seated().saturating_add(1).saturating_add(leased_in).max(lanes).max(1); let budget = self.plan_budget_bytes.load(Ordering::Relaxed); - let fitted = footprint_for(model).map(|fp| fp.window_within(budget, sequences)); - let per_sequence = match fitted.filter(|tokens| *tokens > 0) { - Some(tokens) => tokens, - None => u32::try_from(u64::from(served_ctx) * u64::from(lanes) / u64::from(sequences.max(1))) - .unwrap_or(served_ctx), // unwrap_or: lanes <= sequences, so the share is at most served_ctx - }; - (per_sequence, sequences) + let plan_pool = u64::from(served_ctx) * u64::from(lanes); + let fit_pool = footprint_for(model) + .map_or(0, |fp| u64::from(fp.window_within(budget, sequences).min(model.context_window)) * u64::from(sequences)); // map_or: no footprint proves no fit beyond the plan's own pool + let pool = plan_pool.max(fit_pool); + // `-c` is the CLI's `slots x per-slot`: the pool carried in that shape, not anyone's window. + let per_slot = u32::try_from(pool / u64::from(sequences)).unwrap_or(u32::MAX); // unwrap_or: a pool over u32 x sequences is no real engine; the CLI caps it + (per_slot, sequences) } pub(super) fn launch_reconciled_plan(&self, launch: ReconcileLaunch) -> Option> { @@ -184,6 +186,7 @@ impl ServingDaemonModule { // lane forever, #175). Read+clear here so exactly one reconcile acts on it. let force_relaunch = self.force_relaunch.clone(); let server = self.server.clone(); + let served_pool = Arc::clone(&self.served_pool); let serving_tx = self.serving_tx.clone(); let verified_target = self.verified_target.clone(); let intent_owner = self.intent.clone(); @@ -334,7 +337,10 @@ impl ServingDaemonModule { let (served_window, served_lanes) = match (served_window > 0, server.launched_on_shared_pool()) { (true, Some(true)) => match server.served_pool_tokens().await { - Ok(pool) => sequence_share(pool, served_lanes, target.model.context_window), + Ok(pool) => { + served_pool.store(pool, Ordering::Relaxed); + sequence_share(pool, served_lanes, target.model.context_window) + } Err(e) => { continuum_base::probe!( target: "continuum_core::modules::serving_daemon", class = "serving.reconcile", @@ -343,10 +349,15 @@ impl ServingDaemonModule { "server ready on the shared pool but its pool is unreadable — \ publishing the gap (no guessed share; retries next tick)", ); + served_pool.store(0, Ordering::Relaxed); (0, served_lanes) } }, - _ => (served_window, served_lanes), + // Fixed slots: the engine's pool is literally its slots, each a full window. + _ => { + served_pool.store(served_window.saturating_mul(served_lanes), Ordering::Relaxed); + (served_window, served_lanes) + } }; // The grant the engine was LAUNCHED with: the spawn fact on the control, or — for // a lane this core did not spawn (ADOPTED; every deploy leaves the lane up for diff --git a/core/continuum-serving/src/modules/serving_daemon/tick.rs b/core/continuum-serving/src/modules/serving_daemon/tick.rs index 17a7cc9f74..6ca3d05093 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tick.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tick.rs @@ -74,6 +74,7 @@ impl ServiceModule for ServingDaemonModule { self.take_reported_wedge(); self.seed_reconcile_pages().await; let _ = self.reconcile_to_plan(); + self.publish_grants(); // Liveness heartbeat (#175 self-heal): on a slow cadence, re-verify that the lane // we believe is `ready` can ACTUALLY decode — the reconcile trusts the published // `ready` forever and would never notice an OOM-poisoned backend otherwise. Off the