Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 21 additions & 16 deletions core/continuum-cognition/src/cognition/persona_workspace/rehome.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -64,32 +65,32 @@ 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).
pub fn rehome_reason_at(
&self,
root: &std::path::Path,
model: &str,
context_window: u32,
window_of: impl Fn(Uuid) -> Option<u32>,
) -> Option<RehomeReason> {
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<RehomeReason> {
self.rehome_reason_at(&crate::paths::continuum_root(), model, context_window)
pub fn rehome_reason(&self, model: &str, window_of: impl Fn(Uuid) -> Option<u32>) -> Option<RehomeReason> {
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`
Expand All @@ -104,7 +105,7 @@ impl PersonaWorkspaceRegistry {
root: &std::path::Path,
adapter: Option<Arc<dyn AIProviderAdapter>>,
model: &str,
context_window: u32,
window_of: impl Fn(Uuid) -> Option<u32>,
) -> usize {
let assignments = self.assignments_at(root);
let cycles = self.cycles.lock();
Expand All @@ -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(&current, model, context_window) else {
continue;
};
Expand Down Expand Up @@ -169,13 +179,8 @@ impl PersonaWorkspaceRegistry {
&self,
adapter: Option<Arc<dyn AIProviderAdapter>>,
model: &str,
context_window: u32,
window_of: impl Fn(Uuid) -> Option<u32>,
) -> 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)
}
}
30 changes: 21 additions & 9 deletions core/continuum-core/src/ipc/start_server/rehome_reconciler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -29,6 +31,7 @@ pub(super) fn spawn_rehome_reconciler(
serving_daemon: &Arc<crate::modules::serving_daemon::ServingDaemonModule>,
) {
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
Expand All @@ -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();
Expand All @@ -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)
Expand All @@ -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"
);
}
});
Expand Down
12 changes: 6 additions & 6 deletions core/continuum-core/src/test_env/mind_integration/remote_lane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,13 @@ async fn rehome_requires_a_readable_local_assignment() {
let replacement: Arc<dyn AIProviderAdapter> = 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"));
Expand Down Expand Up @@ -104,17 +104,17 @@ 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);
assert!(Arc::ptr_eq(&before.adapter, &after.adapter), "a window-only correction keeps her adapter");
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");
}

Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/capacity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))]
Expand Down
146 changes: 146 additions & 0 deletions core/continuum-engine/src/capacity/window_grant.rs
Original file line number Diff line number Diff line change
@@ -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<uuid::Uuid, u32>,
/// 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<uuid::Uuid>,
}

impl PoolGrants {
/// Her grant, when she is one of the minds on this pool.
pub fn grant_for(&self, persona: uuid::Uuid) -> Option<u32> {
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<K> {
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<K> {
fn grant(&mut self, demands: &[Demand<K>], held: &BTreeMap<K, u32>, pool_tokens: u32) -> BTreeMap<K, u32>;
}

/// 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<K: Ord + Copy> WindowPolicy<K> for DemandFollowing {
fn grant(
&mut self,
demands: &[Demand<K>],
held: &BTreeMap<K, u32>,
pool_tokens: u32,
) -> BTreeMap<K, u32> {
// 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<K>| 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<u32> {
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>() <= u64::from(pool));
assert_eq!(grants[&2], 2 * grants[&3], "the rest share by need: {grants:?}");
}
}
Loading
Loading