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
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ use crate::cognition::rag_budget::RagSource;
pub mod checkpoint_adoption;

mod rehome;
pub use rehome::RehomeReason;

pub use crate::cognition::handoff::SaveReason;

Expand Down
187 changes: 143 additions & 44 deletions core/continuum-cognition/src/cognition/persona_workspace/rehome.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Serving-edge model binding updates for registered residents.
//! Serving-edge model binding updates for registered residents: every LOCAL resident is
//! bound to exactly what serving reports (model AND window), corrected per persona.
use super::PersonaWorkspaceRegistry;
use crate::ai::adapter::AIProviderAdapter;
use crate::cognition::llm_deliberation_faculty::ModelBinding;
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

Expand All @@ -10,55 +13,110 @@ enum Assignment {
Unreadable,
}

/// Why a local resident's binding moves to the served one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RehomeReason {
/// Serving reports a different model: a new shared adapter is required.
ModelChanged,
/// Same model, a different served window (a resident materialized before the
/// snapshot was ready keeps her provisional window until this corrects it).
WindowChanged,
}

impl RehomeReason {
fn of(binding: &ModelBinding, model: &str, context_window: u32) -> Option<Self> {
if binding.requested_model() != model {
Some(Self::ModelChanged)
} else if binding.context_window != context_window {
Some(Self::WindowChanged)
} else {
None
}
}

fn as_str(self) -> &'static str {
match self {
Self::ModelChanged => "model_changed",
Self::WindowChanged => "window_changed",
}
}
}

impl PersonaWorkspaceRegistry {
/// Re-home EVERY resident persona onto a newly served model — atomically swap
/// the shared {adapter, model, context_window} binding on each cycle (see
/// [`crate::cognition::workspace::WorkspaceCycle::rebind_model`]). On a single-serve host ALL personas share
/// the ONE served model (INFERENCE-LANES-REALISTIC: "one base model, N persona
/// lanes"), so a served-model change re-homes them together through the ONE
/// shared `adapter` — no per-persona HTTP init. Each mind's genome + working
/// memory + admission + hippocampus are UNTOUCHED (flip-in-place, not rebuild):
/// the same continuous personas now deliberate through the new model. Returns
/// how many minds were re-homed. Driven by the serving-snapshot reconciler
/// (`ipc/mod.rs`) ONLY on an actual model change. The store is a wait-free
/// `ArcSwap` under the cycles lock — NO await held across it.
/// See [[seamless-persona-failover-model-and-genome]].
/// The assignment of every registered resident, read once. A citizen whose brain is
/// assigned OFF-BOX keeps her remote binding: the local lane coming up is not her
/// model changing (card 1d2f65e7 slice 2).
fn assignments_at(&self, root: &std::path::Path) -> HashMap<Uuid, Assignment> {
let templates = self.templates.lock();
templates
.iter()
.map(|(id, cfg)| {
let assignment = match crate::cognition::extensions::is_remote_bound(root, &cfg.persona_name) {
Ok(false) => Assignment::Local,
Ok(true) => Assignment::Remote,
Err(error) => {
tracing::error!(persona = %cfg.persona_name, %error, "re-home refused: preserving current binding");
Assignment::Unreadable
}
};
(*id, assignment)
})
.collect()
}

/// What the served `(model, context_window)` asks 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,
) -> 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))
.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)
}

/// Bind EVERY local resident to the served `(model, context_window)` — 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`
/// (no per-persona HTTP init; INFERENCE-LANES-REALISTIC: one base model, N persona
/// lanes); a window-only change keeps her own adapter and moves the window. Genome,
/// working memory, admission and hippocampus are UNTOUCHED (flip-in-place). Returns
/// how many minds were rebound. Driven by the serving-snapshot reconciler on every
/// ready snapshot. The store is a wait-free `ArcSwap` under the cycles lock — NO
/// await held across it. See [[seamless-persona-failover-model-and-genome]].
pub fn re_home_all_at(
&self,
root: &std::path::Path,
adapter: Arc<dyn AIProviderAdapter>,
model: Option<String>,
adapter: Option<Arc<dyn AIProviderAdapter>>,
model: &str,
context_window: u32,
) -> usize {
// A citizen whose brain is assigned OFF-BOX keeps her remote binding: the
// local lane coming up is not her model changing (card 1d2f65e7 slice 2).
let assignments: std::collections::HashMap<Uuid, Assignment> = {
let templates = self.templates.lock();
templates
.iter()
.map(|(id, cfg)| {
let assignment = match crate::cognition::extensions::is_remote_bound(root, &cfg.persona_name) {
Ok(false) => Assignment::Local,
Ok(true) => Assignment::Remote,
Err(error) => {
tracing::error!(persona = %cfg.persona_name, %error, "re-home refused: preserving current binding");
Assignment::Unreadable
}
};
(*id, assignment)
})
.collect()
};
let assignments = self.assignments_at(root);
let cycles = self.cycles.lock();
let mut rehomed = 0usize;
for (id, entry) in cycles.iter() {
let reason = match assignments.get(id) {
let kept = match assignments.get(id) {
Some(Assignment::Local) => None,
Some(Assignment::Remote) => Some("remote"),
Some(Assignment::Unreadable) => Some("unreadable"),
None => Some("missing_template"),
};
if let Some(reason) = reason {
if let Some(reason) = kept {
continuum_base::probe!(
class = "persona.rehome.kept_binding",
persona_id = %id,
Expand All @@ -67,16 +125,57 @@ impl PersonaWorkspaceRegistry {
);
continue;
}
entry
.cycle
.rebind_model(crate::cognition::llm_deliberation_faculty::ModelBinding {
adapter: Arc::clone(&adapter),
model: model.clone(),
context_window,
});
let Some(current) = entry.cycle.current_binding() else {
continue; // no deliberation faculty shared a binding in: nothing to rebind.
};
let Some(reason) = RehomeReason::of(&current, model, context_window) else {
continue;
};
let next_adapter = match (reason, &adapter) {
(RehomeReason::ModelChanged, Some(shared)) => Arc::clone(shared),
(RehomeReason::ModelChanged, None) => {
continuum_base::probe!(
class = "persona.rehome.kept_binding",
persona_id = %id,
reason = "model_changed_without_adapter",
"re-home skipped: the served model changed after the adapter decision; the next tick rebuilds it"
);
continue;
}
(RehomeReason::WindowChanged, _) => Arc::clone(&current.adapter),
};
continuum_base::probe!(
class = "persona.rehome",
persona_id = %id,
reason = reason.as_str(),
old_model = %current.requested_model(),
new_model = %model,
old_window = current.context_window,
new_window = context_window,
"resident rebound to the served binding"
);
entry.cycle.rebind_model(ModelBinding {
adapter: next_adapter,
model: Some(model.to_string()),
context_window,
});
rehomed += 1;
}
rehomed
}
}

/// [`re_home_all_at`](Self::re_home_all_at) under this process's continuum root.
pub fn re_home_all(
&self,
adapter: Option<Arc<dyn AIProviderAdapter>>,
model: &str,
context_window: u32,
) -> usize {
self.re_home_all_at(
&crate::paths::continuum_root(),
adapter,
model,
context_window,
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -632,21 +632,6 @@ impl PersonaWorkspaceRegistry {
Some((Arc::clone(&cfg.admission), adapter, model))
}

/// Rebind verified local residents on a serving change; preserve remote or unreadable assignments.
pub fn re_home_all(
&self,
adapter: Arc<dyn AIProviderAdapter>,
model: Option<String>,
context_window: u32,
) -> usize {
self.re_home_all_at(
&crate::paths::continuum_root(),
adapter,
model,
context_window,
)
}

/// How many persona minds are resident.
pub fn len(&self) -> usize {
self.cycles.lock().len()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,13 @@ impl WorkspaceCycle {
.map(|handle| handle.load().adapter.clone())
}

/// The whole live binding {adapter, model, window} as ONE read — what the re-home
/// owner compares against the served snapshot. `None` for a cycle with no
/// deliberation faculty.
pub fn current_binding(&self) -> Option<Arc<ModelBinding>> {
self.model_binding.as_ref().map(|handle| handle.load_full())
}

/// The adapter AND the served-model id it must be asked for, as one read of
/// the shared binding. Background regions must send BOTH: the model id
/// selects the route/template on the serving side, and omitting it produced
Expand Down Expand Up @@ -245,9 +252,8 @@ impl WorkspaceCycle {
/// id the next generation asks for (`ModelBinding.model` doc: `None` → the
/// adapter's default). This resolution matters live: the boot upstart binds
/// `model: None` (the shared served adapter already carries the active model
/// as its default), and the re-home reconciler (`ipc/mod.rs`) adopts the
/// FIRST served model as baseline *without* a rebind — so on a stable host
/// the explicit id stays `None` forever. Reporting the raw field left every
/// as its default), and a binding stored without an explicit id keeps it
/// `None` until a re-home names one. Reporting the raw field left every
/// live roster LOADOUT as "ctx only, no model name" (the tile regression this
/// fixes). An adapter with an empty default resolves to honest-absent.
pub fn model_loadout(&self) -> Option<(Option<String>, u32)> {
Expand Down
Loading
Loading