diff --git a/core/continuum-engine/src/ai/openai_adapter/stream.rs b/core/continuum-engine/src/ai/openai_adapter/stream.rs index 17cd348388..7a060ec3f2 100644 --- a/core/continuum-engine/src/ai/openai_adapter/stream.rs +++ b/core/continuum-engine/src/ai/openai_adapter/stream.rs @@ -212,7 +212,10 @@ impl OpenAICompatibleAdapter { })?; // The endpoint's own permits, shared by every adapter and the learner (card 23069702). let endpoint_permits = crate::inference::slots::directory().endpoint(root).concurrency().bound(); - let adm = crate::inference::turn_admission::admit_turn( + // Her state streams in while she waits for a lane (fork #139: a mind on flash is inserted into a parked + // sequence, so her switch is a sequence move), only from an engine that declared resident minds. + let stream_in = turn_key.filter(|_| class.holds_a_page()).zip(pool.resident_minds()); + let admit = crate::inference::turn_admission::admit_turn( endpoint_permits, class, turn_key, @@ -221,8 +224,21 @@ impl OpenAICompatibleAdapter { root, approx_tokens, crate::inference::turn_admission::AdmissionPatience::for_turn(), - ) - .await + ); + let adm = match stream_in { + None => admit.await, + Some((key, minds)) => { + // Admission first: a turn admitted at once never streams. The stream lives only while she + // waits, and is dropped with her wait (admitted or cancelled), so it never outlives its turn. + let mut admit = std::pin::pin!(admit); + let stream = crate::inference::minds::prefetch(&self.client, root, minds, key); + tokio::select! { + biased; + adm = &mut admit => adm, + () = stream => admit.await, + } + } + } .map_err(crate::ai::inference_error::InferenceError::Unavailable)?; let scratch = adm.scratch_slot(); // Only a turn that names its page owns a slot. A Turn with no persona (or a Fork @@ -273,6 +289,11 @@ impl OpenAICompatibleAdapter { if let Some(slot) = placement { if let Some(obj) = body.as_object_mut() { obj.insert("id_slot".to_string(), json!(slot)); + // the mind this turn is (fork #139): the engine switches minds on a lane by sequence moves, + // never through its prompt cache; an engine without minds ignores the field + if let (true, Some(key)) = (keyed_turn, turn_key.as_ref()) { + obj.insert("page".to_string(), json!(key.engine_id().simple().to_string())); + } } if let (true, Some(persona)) = ( keyed_turn, diff --git a/core/continuum-engine/src/inference/llama_server/control.rs b/core/continuum-engine/src/inference/llama_server/control.rs index 7b5e83a6e8..c91d7d5465 100644 --- a/core/continuum-engine/src/inference/llama_server/control.rs +++ b/core/continuum-engine/src/inference/llama_server/control.rs @@ -255,6 +255,10 @@ pub trait LlamaServerControl: Send + Sync { None } + /// The resident minds the next launch keeps beside its lanes (`--minds`, fork #139): the seated minds plus + /// the learner's side sequence. Only the resident lane's controller holds them; no other lane is asked. + fn seat_minds(&self, _minds: std::num::NonZeroU32) {} + async fn serve_if_current( &self, target: &ServingTarget, diff --git a/core/continuum-engine/src/inference/llama_server/control_impl.rs b/core/continuum-engine/src/inference/llama_server/control_impl.rs index 53c48b37f6..63a74671a9 100644 --- a/core/continuum-engine/src/inference/llama_server/control_impl.rs +++ b/core/continuum-engine/src/inference/llama_server/control_impl.rs @@ -477,6 +477,10 @@ impl LlamaServerControl for LlamaServerProcess { self.last_started.lock().clone() } + fn seat_minds(&self, minds: std::num::NonZeroU32) { + self.seated_minds.store(minds.get(), std::sync::atomic::Ordering::Relaxed); + } + async fn serve_if_current( &self, target: &ServingTarget, diff --git a/core/continuum-engine/src/inference/llama_server/genome.rs b/core/continuum-engine/src/inference/llama_server/genome.rs index f71995c27b..0dc00be60a 100644 --- a/core/continuum-engine/src/inference/llama_server/genome.rs +++ b/core/continuum-engine/src/inference/llama_server/genome.rs @@ -21,7 +21,7 @@ pub(super) static ENGINE_PROBES: parking_lot::Mutex Option { /// PURE: what the record says about `bin`: its answer, no when it did not answer, nothing when it /// was never asked. pub(super) fn answer_for(probes: &BTreeMap, bin: &str) -> Option { - probes.get(bin).map(|outcome| matches!(outcome, ProbeOutcome::Answered { train_dir: true })) + probes.get(bin).map(|outcome| matches!(outcome, ProbeOutcome::Answered { train_dir: true, .. })) } /// PURE: what a decision may rest on: `bin`'s answer when it answered, else nothing (never asked, /// or asked without an answer), and the caller asks it now. pub(super) fn train_dir_known(probes: &BTreeMap, bin: &str) -> Option { match probes.get(bin) { - Some(ProbeOutcome::Answered { train_dir }) => Some(*train_dir), + Some(ProbeOutcome::Answered { train_dir, .. }) => Some(*train_dir), _ => None, } } @@ -63,6 +63,17 @@ pub(super) fn engine_help_lists_train_dir(help: &str) -> bool { help.lines().any(|l| l.trim_start().starts_with("--train-dir")) } +/// The engine keeps resident minds as parked sequences (`--minds`, fork #139): a mind switch is a sequence +/// move, never a serialization. +pub(super) fn engine_help_lists_minds(help: &str) -> bool { + help.lines().any(|l| l.trim_start().starts_with("--minds")) +} + +/// Whether `bin` accepts `--minds`. "Not asked yet" reads as no: an older engine refuses to start with it. +pub fn engine_accepts_minds(bin: &str) -> bool { + matches!(ENGINE_PROBES.lock().get(bin), Some(ProbeOutcome::Answered { minds: true, .. })) +} + /// Where every lane's `POST /train` writes its adapters (`--train-dir`). One directory /// for all lanes: a job names its output `.gguf`, and the engine trainer moves diff --git a/core/continuum-engine/src/inference/llama_server/kv_support.rs b/core/continuum-engine/src/inference/llama_server/kv_support.rs index b957de4dc4..b53021c899 100644 --- a/core/continuum-engine/src/inference/llama_server/kv_support.rs +++ b/core/continuum-engine/src/inference/llama_server/kv_support.rs @@ -16,6 +16,7 @@ pub(super) async fn ensure_engine_kv_support_recorded(bin: &str, mut command: to return; } let mut train_dir = false; + let mut minds = false; command.arg("--help"); // owned (continuum_process::run_owned): a help probe that hangs is ended with anything it started let probe = continuum_process::run_owned(command, Some(Duration::from_secs(10)), "engine-help-probe", std::sync::Arc::default()).await; @@ -30,6 +31,7 @@ pub(super) async fn ensure_engine_kv_support_recorded(bin: &str, mut command: to text.push('\n'); text.push_str(&String::from_utf8_lossy(&out.stderr.bytes)); train_dir = engine_help_lists_train_dir(&text); + minds = super::genome::engine_help_lists_minds(&text); match crate::inference::kv_cache_plan::parse_engine_kv_support(&text) { Some(v) => ("answered", Some(v), String::new()), None => ("did_not_enumerate", None, String::new()), @@ -40,7 +42,7 @@ pub(super) async fn ensure_engine_kv_support_recorded(bin: &str, mut command: to crate::inference::kv_cache_plan::record_engine_quantized_kv_support(support); // None = unanswered: the backend table decides // This binary's entry alone, written whole: what it said, or that it did not answer. let outcome_of_probe = match matches!(outcome, "answered" | "did_not_enumerate") { - true => super::genome::ProbeOutcome::Answered { train_dir }, + true => super::genome::ProbeOutcome::Answered { train_dir, minds }, false => super::genome::ProbeOutcome::Unanswered, }; super::genome::ENGINE_PROBES.lock().insert(bin.to_owned(), outcome_of_probe); diff --git a/core/continuum-engine/src/inference/llama_server/prepare.rs b/core/continuum-engine/src/inference/llama_server/prepare.rs index 2b76d8ecf0..ba85a38141 100644 --- a/core/continuum-engine/src/inference/llama_server/prepare.rs +++ b/core/continuum-engine/src/inference/llama_server/prepare.rs @@ -306,7 +306,9 @@ impl LlamaServerProcess { max_ubatch: target.model.serving.max_ubatch, reasoning_budget: target.model.serving.reasoning_budget, }); - let mut invocation = super::shared_pool::on_shared_pool(invocation); + let seated = std::num::NonZeroU32::new(self.seated_minds.load(std::sync::atomic::Ordering::Relaxed)); + let minds = seated.filter(|_| super::genome::engine_accepts_minds(&bin)); + let mut invocation = super::shared_pool::on_shared_pool(invocation, minds); // MoE glass-box env seam (#278): when expert paging is active, the DAEMON // hands the fork its capture + plan file locations. Previously these envs // existed only when an operator hand-exported them before booting the @@ -492,7 +494,8 @@ impl LlamaServerProcess { let ambiguous_adapter = lora_paths .iter() .any(|p| p.to_str().is_none_or(|p| p.contains(','))); - let local_inputs = if !cfg!(windows) || engine_install.is_none() { + // the receipt is made only where the engine contract exists (`EngineInstallReceipt::load`): none elsewhere + let local_inputs = if engine_install.is_none() { Err( "exact restoration requires original Windows application and local input pins" .into(), diff --git a/core/continuum-engine/src/inference/llama_server/process.rs b/core/continuum-engine/src/inference/llama_server/process.rs index 266f588e69..ddc2958017 100644 --- a/core/continuum-engine/src/inference/llama_server/process.rs +++ b/core/continuum-engine/src/inference/llama_server/process.rs @@ -93,6 +93,9 @@ pub struct LlamaServerProcess { /// what the running process was given, read by the serving daemon into the /// snapshot — never the plan's latest derivation of what it would give. pub(super) launched_prompt_cache_mib: std::sync::atomic::AtomicU32, + /// Resident minds the next launch keeps beside its lanes as parked sequences (`--minds`, fork #139), seated + /// by the serving daemon ([`super::LlamaServerControl::seat_minds`]). 0: none (every ephemeral lane). + pub(super) seated_minds: std::sync::atomic::AtomicU32, } @@ -160,6 +163,7 @@ impl LlamaServerProcess { smoke_proven_thinking: std::sync::atomic::AtomicBool::new(false), mmproj_on_lane: std::sync::atomic::AtomicU8::new(0), launched_prompt_cache_mib: std::sync::atomic::AtomicU32::new(0), + seated_minds: std::sync::atomic::AtomicU32::new(0), } } @@ -198,6 +202,7 @@ impl LlamaServerProcess { smoke_proven_thinking: std::sync::atomic::AtomicBool::new(false), mmproj_on_lane: std::sync::atomic::AtomicU8::new(0), launched_prompt_cache_mib: std::sync::atomic::AtomicU32::new(0), + seated_minds: std::sync::atomic::AtomicU32::new(0), } } diff --git a/core/continuum-engine/src/inference/llama_server/shared_pool.rs b/core/continuum-engine/src/inference/llama_server/shared_pool.rs index 45b6ce0d2b..dbb89cc45f 100644 --- a/core/continuum-engine/src/inference/llama_server/shared_pool.rs +++ b/core/continuum-engine/src/inference/llama_server/shared_pool.rs @@ -22,11 +22,20 @@ const SHARED_POOL_SHORT: &str = "-kvu"; /// tokens, Aris 20,962 at 38 tok/s, Aiko 62,026), while back-to-back turns reused 28-38k each. const KEEP_IDLE_SLOTS: &str = "--no-cache-idle-slots"; +/// The engine's resident minds beside its lanes (fork #139): each a parked sequence of the pool, so a +/// mind switch is a sequence move in milliseconds (parked) or through flash, never a serialization. +const RESIDENT_MINDS: &str = "--minds"; + /// Launch on the shared pool: every sequence draws on all of `-c`, and an idle one keeps what -/// she holds until the core pages her. -pub(super) fn on_shared_pool(mut invocation: LaneInvocation) -> LaneInvocation { +/// she holds until the core pages her. `minds`: parked sequence ids beside the lanes, given only to an engine +/// that lists `--minds`: the seated minds plus one side sequence for learning (`LlamaServerControl::seat_minds`). +pub(super) fn on_shared_pool(mut invocation: LaneInvocation, minds: Option) -> LaneInvocation { invocation.args.push(SHARED_POOL.to_string()); invocation.args.push(KEEP_IDLE_SLOTS.to_string()); + if let Some(n) = minds { + invocation.args.push(RESIDENT_MINDS.to_string()); + invocation.args.push(n.to_string()); + } invocation } diff --git a/core/continuum-engine/src/inference/llama_server/tests.rs b/core/continuum-engine/src/inference/llama_server/tests.rs index 3ab581540f..a08117837e 100644 --- a/core/continuum-engine/src/inference/llama_server/tests.rs +++ b/core/continuum-engine/src/inference/llama_server/tests.rs @@ -209,6 +209,7 @@ impl LlamaServerControl for FakeControl { allocated_tokens: u64::from(self.served_window.saturating_mul(lanes)), max_tokens_per_sequence: u64::from(self.served_window), sequence_capacity: u64::from(lanes), + resident_minds: None, }) } async fn served_lanes(&self) -> Result { diff --git a/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs b/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs index 3b48c07efa..b3732ec210 100644 --- a/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs +++ b/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs @@ -120,8 +120,10 @@ fn the_engine_launches_on_one_shared_pool() { Path::new("fixture.gguf"), planned.model_id(), "127.0.0.1", 1, planned.parallel_lanes(), planned.served_total_ctx(), planned.host_prompt_cache_mib, Path::new("pages"), - )); + ), std::num::NonZeroU32::new(planned.parallel_lanes())); assert_eq!(invocation.value_of("-c"), Some("290560")); assert_eq!(invocation.value_of("--parallel"), Some("5")); + // what this catches: a mind switch serialized through the prompt cache because the engine had no parked ids + assert_eq!(invocation.value_of("--minds"), Some("5"), "an engine that lists --minds keeps one parked id per lane"); assert_eq!(super::super::shared_pool::pool_launch(&invocation.args), super::super::PoolLaunch::Shared, "the launch and the read-back agree"); } diff --git a/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs b/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs index a48b989338..e5e7bca91d 100644 --- a/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs +++ b/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs @@ -378,7 +378,7 @@ fn an_adopted_engines_report_reads_back_as_the_genes_it_holds() { #[test] fn a_train_dir_answer_is_about_the_binary_asked_and_no_other() { let probes = std::collections::BTreeMap::from([ - ("/slots/engine-a/llama-server".to_string(), ProbeOutcome::Answered { train_dir: true }), + ("/slots/engine-a/llama-server".to_string(), ProbeOutcome::Answered { train_dir: true, minds: false }), ("/slots/engine-b/llama-server".to_string(), ProbeOutcome::Unanswered), ]); assert_eq!(answer_for(&probes, "/slots/engine-a/llama-server"), Some(true)); @@ -394,8 +394,8 @@ fn a_train_dir_answer_is_about_the_binary_asked_and_no_other() { #[test] fn an_in_place_decision_rests_only_on_an_answer() { let probes = std::collections::BTreeMap::from([ - ("answered-yes".to_string(), ProbeOutcome::Answered { train_dir: true }), - ("answered-no".to_string(), ProbeOutcome::Answered { train_dir: false }), + ("answered-yes".to_string(), ProbeOutcome::Answered { train_dir: true, minds: false }), + ("answered-no".to_string(), ProbeOutcome::Answered { train_dir: false, minds: false }), ("timed-out".to_string(), ProbeOutcome::Unanswered), ]); assert_eq!(train_dir_known(&probes, "answered-yes"), Some(true)); diff --git a/core/continuum-engine/src/inference/minds.rs b/core/continuum-engine/src/inference/minds.rs new file mode 100644 index 0000000000..a3a27a2182 --- /dev/null +++ b/core/continuum-engine/src/inference/minds.rs @@ -0,0 +1,28 @@ +//! Resident minds on the engine (fork #139): a mind switch is a sequence move, never a serialization. +//! +//! An engine that declares `resident_minds` on `/props` keeps every mind it serves as a sequence of its unified +//! KV pool (parked when another mind holds the lane) or, when the pool needs her cells, as a page on flash it maps +//! back in. A turn names its mind (`"page"`, [`super::slots::PageKey::engine_id`]) so the engine moves the right +//! sequence; and while she waits for a lane her state streams in, the way a game engine streams what the camera +//! needs next, so her switch is the sub-millisecond sequence move. + +use super::slots::PageKey; +use super::weight_residency::ResidentMinds; + +/// Bring `key`'s mind into the pool of the engine at `root` (`POST /minds/prefetch`), carrying the incarnation +/// token that engine declared (`minds`), so a replaced engine refuses it. The turn waiting for a lane owns this +/// future: admitted, or cancelled, it is dropped with her wait; it never runs for a turn that did not wait. +pub(crate) async fn prefetch(client: &reqwest::Client, root: &str, minds: ResidentMinds, key: PageKey) { + let url = format!("{}/minds/prefetch", root.trim_end_matches('/')); + let body = serde_json::json!({ "page": key.engine_id().simple().to_string(), "incarnation": minds.incarnation }); + let outcome = match client.post(&url).json(&body).send().await { + Ok(response) => response.status().as_u16().to_string(), + Err(e) => e.to_string(), + }; + continuum_base::probe!( + class = "inference.minds.prefetch", + page = %key, + outcome = outcome.as_str(), + "her state streamed in while she waited for a lane (the engine's reply names where she is)" + ); +} diff --git a/core/continuum-engine/src/inference/mod.rs b/core/continuum-engine/src/inference/mod.rs index 50d05004e3..ff2626e117 100644 --- a/core/continuum-engine/src/inference/mod.rs +++ b/core/continuum-engine/src/inference/mod.rs @@ -39,6 +39,7 @@ pub mod handle_store; pub mod kv_cache_plan; pub mod kv_quant; pub mod lane_args; +pub mod minds; pub mod lane_demand; pub mod lane_health; pub mod lane_send; diff --git a/core/continuum-engine/src/inference/slots/citizen_slots.rs b/core/continuum-engine/src/inference/slots/citizen_slots.rs index 9d93787cba..aa37ed20f8 100644 --- a/core/continuum-engine/src/inference/slots/citizen_slots.rs +++ b/core/continuum-engine/src/inference/slots/citizen_slots.rs @@ -194,6 +194,10 @@ pub struct KvSlotPool { /// one it verified (`slots/discover.rs`), with or without a page ledger: the identity every /// endpoint admission on this pool is bound to (`EndpointAdmission::incarnation`). pub(super) incarnation: std::sync::OnceLock<(u32, u64)>, + /// The engine's resident minds (fork #139) as its `/props` declared them, recorded ONCE: by discovery when it + /// installs the pool, or by the first discovery of a pool an owned spawn published (a spawn knows its launch + /// contract, not the engine's declaration). Unset means not yet declared, never "no minds". + pub(super) resident_minds: std::sync::OnceLock>, /// Numbers each change of [`Self::saved`] for the ledger, so a write taken outside the /// lock never replaces a newer one ([`Self::ledger_snapshot`]). pub(super) ledger_generation: AtomicU64, diff --git a/core/continuum-engine/src/inference/slots/discover.rs b/core/continuum-engine/src/inference/slots/discover.rs index 6b82d6e848..357d11ba0f 100644 --- a/core/continuum-engine/src/inference/slots/discover.rs +++ b/core/continuum-engine/src/inference/slots/discover.rs @@ -42,6 +42,9 @@ pub enum PoolDiscoveryMiss { /// The pool already installed for this server disagrees with what `/props` reports. #[error("installed pool has {installed} slots, props reports {props}")] GeometryMismatch { installed: u32, props: u32 }, + /// The installed pool's resident-minds declaration (or its incarnation token) is not this `/props`'s. + #[error("installed pool's resident minds disagree with props")] + MindsMismatch, /// The page-admission negotiation refused this pool. #[error("page admission refused this pool")] PageAdmissionRefused, @@ -71,6 +74,7 @@ impl PoolDiscoveryMiss { Self::NoGeometry => "no_geometry", Self::Superseded => "superseded", Self::GeometryMismatch { .. } => "geometry_mismatch", + Self::MindsMismatch => "minds_mismatch", Self::PageAdmissionRefused => "page_admission_refused", } } @@ -197,13 +201,18 @@ impl SlotDirectory { // The directory arbitrates the probe race: only the first writer installs the pool, once // per SERVER, and it installs it with its page store already settled. A pool known here // was published by that writer, so no caller ever admits against an undecided store. + // whether this engine owns mind switches, declared in the same body (never inferred from a 404) + let minds = crate::inference::weight_residency::ContextGeometry::from_props(&body).and_then(|g| g.resident_minds); let pool = match existing_pool { Some(pool) => pool, - None => self.install_settled_pool(root, n_slots, |pool| settle_adopted_page_store(pool, root)), + None => self.install_settled_pool(root, n_slots, minds, |pool| settle_adopted_page_store(pool, root)), }; if pool.n_slots() != n_slots { return Err(Miss::GeometryMismatch { installed: pool.n_slots(), props: n_slots }); // they must agree } + if !pool.declare_resident_minds(minds) { + return Err(Miss::MindsMismatch); // the installed pool's paging authority belongs to another engine + } if !self.negotiate_page_admission(root, &pool, discovery_generation, body.get("slot_save_size_version")).await { return Err(Miss::PageAdmissionRefused); } @@ -229,9 +238,10 @@ impl SlotDirectory { &self, root: &str, n_slots: u32, + minds: Option, settle: impl FnOnce(&KvSlotPool) -> SettledPageStore, ) -> Arc { - let candidate = Arc::new(KvSlotPool::new(root, n_slots)); + let candidate = Arc::new(KvSlotPool::new(root, n_slots).with_resident_minds(minds)); let settled = settle(&candidate); let pool = self.install_pool(root, || Arc::clone(&candidate)); if Arc::ptr_eq(&pool, &candidate) { diff --git a/core/continuum-engine/src/inference/slots/engine_generation.rs b/core/continuum-engine/src/inference/slots/engine_generation.rs index 986e4978d1..f8d6bd77c8 100644 --- a/core/continuum-engine/src/inference/slots/engine_generation.rs +++ b/core/continuum-engine/src/inference/slots/engine_generation.rs @@ -764,6 +764,13 @@ impl SlotDirectory { if body.get("total_slots").and_then(serde_json::Value::as_u64) != Some(pool.n_slots() as u64) { return Err("page-write capabilities do not identify this pool geometry".into()); } + // Admission is granted only on a pool whose minds the engine has declared: this path can precede the first + // adapter discovery (a lifecycle checkpoint), and a granted admission is discovery's fast path, so an + // undeclared pool admitted here would be read as core-paged minds (M5 2026-11-17). + let minds = crate::inference::weight_residency::ContextGeometry::from_props(&body).and_then(|g| g.resident_minds); + if !pool.declare_resident_minds(minds) { + return Err("the engine's declared resident minds differ from this pool's record".into()); + } if !self.negotiate_page_admission(root, &pool, generation, body.get("slot_save_size_version")).await { return Err("engine changed during page-write discovery".into()); } diff --git a/core/continuum-engine/src/inference/slots/kv_slot_pool.rs b/core/continuum-engine/src/inference/slots/kv_slot_pool.rs index 7a03e90118..d5ac3b753a 100644 --- a/core/continuum-engine/src/inference/slots/kv_slot_pool.rs +++ b/core/continuum-engine/src/inference/slots/kv_slot_pool.rs @@ -63,6 +63,7 @@ impl KvSlotPool { scratch_released: Arc::new(tokio::sync::Notify::new()), ledger: std::sync::OnceLock::new(), incarnation: std::sync::OnceLock::new(), + resident_minds: std::sync::OnceLock::new(), ledger_generation: AtomicU64::new(0), sequences: Mutex::new(LiveSequences::default()), } @@ -130,6 +131,25 @@ impl KvSlotPool { self.incarnation.get().copied() } + /// Whether this pool's engine owns mind switches (fork #139), as its `/props` declared. `None`: the core + /// pages minds itself, or the engine has not declared yet. + pub(crate) fn resident_minds(&self) -> Option { + self.resident_minds.get().copied().flatten() + } + + /// This pool, for an engine that declared resident minds on the `/props` that installs it. + pub(super) fn with_resident_minds(mut self, minds: Option) -> Self { + self.resident_minds = std::sync::OnceLock::from(minds); // a fresh pool: born holding its first and only declaration + self + } + + /// Record the engine's declared minds on first sight, or check them against the record: `false` only when + /// this pool already recorded a DIFFERENT declaration (its paging authority belongs to another engine). A pool + /// an owned spawn published has no record yet; its first discovery records the engine's own declaration. + pub(super) fn declare_resident_minds(&self, minds: Option) -> bool { + *self.resident_minds.get_or_init(|| minds) == minds + } + pub fn n_slots(&self) -> u32 { self.n_slots } diff --git a/core/continuum-engine/src/inference/slots/page_key.rs b/core/continuum-engine/src/inference/slots/page_key.rs index 3f79762231..d567d4c699 100644 --- a/core/continuum-engine/src/inference/slots/page_key.rs +++ b/core/continuum-engine/src/inference/slots/page_key.rs @@ -90,6 +90,22 @@ impl PageKey { } } +/// The namespace a fork's engine id is derived in, so it can never equal a mind's (her persona id). +const FORK_ENGINE_NAMESPACE: Uuid = Uuid::from_u128(0x0dcaba2a_7457_5f3c_9be6_64cb21c5bfea); + +impl PageKey { + /// The 128-bit id the engine keeps this page's resident mind under (fork #139: `"page"` on a request, + /// `/minds/prefetch`). A mind is her persona; a fork is derived from (persona, room) in its own namespace. + pub fn engine_id(&self) -> Uuid { + match self { + Self::Mind(m) => m.persona(), + Self::Fork(k) => { + Uuid::new_v5(&FORK_ENGINE_NAMESPACE, &[*k.persona.as_bytes(), *k.room.as_bytes()].concat()) + } + } + } +} + /// For probes only; never a key. impl fmt::Display for PageKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/core/continuum-engine/src/inference/slots/tests/discover.rs b/core/continuum-engine/src/inference/slots/tests/discover.rs index d0285719f0..07923519b2 100644 --- a/core/continuum-engine/src/inference/slots/tests/discover.rs +++ b/core/continuum-engine/src/inference/slots/tests/discover.rs @@ -102,7 +102,7 @@ async fn an_admission_racing_the_ledger_adoption_restores_her_page() -> Result<( let first_probe = tokio::task::spawn_blocking({ let (dir, pages) = (Arc::clone(&dir), pages.path().to_path_buf()); move || { - dir.install_settled_pool(root, 2, |pool| { + dir.install_settled_pool(root, 2, None, |pool| { let _ = reading.send(()); let _ = resume.recv(); // test: held until the admission has looked let (adoption, snapshot) = @@ -125,7 +125,112 @@ async fn an_admission_racing_the_ledger_adoption_restores_her_page() -> Result<( assert!(pool.plan_paging(slot, aris).restore, "her first turn after the restart restores, never a cold prefill"); // A second settled install (a racing probe) loses: the published pool and its settlement stand. - let second = dir.install_settled_pool(root, 2, |_| SettledPageStore { adoption: Err(NotAdopted::NoLiveLaneRecord), snapshot: None }); + let second = dir.install_settled_pool(root, 2, None, |_| SettledPageStore { adoption: Err(NotAdopted::NoLiveLaneRecord), snapshot: None }); assert!(Arc::ptr_eq(&second, &pool), "one pool per root"); Ok(()) } + +// what this catches: the M5 2026-11-17 04:20Z outage (regression for core 37a354cf2, #6087). An owned spawn +// publishes its pool at readiness from its launch contract, which carries no minds declaration; discovery then +// compared that pool's "no minds" to the engine's declared minds and refused EVERY generation (minds_mismatch, +// ~10 re-probes a second) for the engine's whole life. The pool's minds are a set-once record of the engine's +// own declaration: a pool with no record takes the first; only a recorded, different declaration mismatches. +#[test] +fn a_pool_records_the_engines_declared_minds_once() { + use crate::inference::weight_residency::ResidentMinds; + let minds = Some(ResidentMinds { lanes: 5, parked_ids: 5, incarnation: 4_077_290_934_432_821_903 }); + let other = Some(ResidentMinds { lanes: 5, parked_ids: 5, incarnation: 7 }); + + let owned = KvSlotPool::new("owned", 5); // as an owned spawn publishes it: no declaration yet + assert_eq!(owned.resident_minds(), None, "undeclared reads as no minds, never as a recorded none"); + assert!(owned.declare_resident_minds(minds), "the first discovery records the engine's declaration"); + assert_eq!(owned.resident_minds(), minds); + assert!(owned.declare_resident_minds(minds), "the same engine's declaration agrees"); + assert!(!owned.declare_resident_minds(other), "another engine's declaration is the mismatch"); + + let discovered = KvSlotPool::new("discovered", 5).with_resident_minds(None); // installed by a /props with no minds + assert!(!discovered.declare_resident_minds(minds), "a recorded 'no minds' is a declaration, not a blank"); +} + +/// A fake engine declaring resident minds on `/props`, and this core's owned spawn of it: a ready generation +/// whose pool was published from the launch contract (no minds declaration yet). +async fn owned_spawn_declaring_minds() -> (String, Arc, tempfile::TempDir, tokio::task::JoinHandle<()>) { + // the fork's /props shape for an engine with resident minds, typed (as the engine writes it) + #[derive(serde::Serialize, Clone)] + struct Minds { enabled: bool, lanes: u64, parked_ids: u64, parked_free: u64, incarnation: u64 } + #[derive(serde::Serialize, Clone)] + struct Geometry { allocated_tokens: u64, max_tokens_per_sequence: u64, sequence_capacity: u64, resident_minds: Minds } + #[derive(serde::Serialize, Clone)] + struct Props { total_slots: u32, context_geometry: Geometry } + let props = Props { + total_slots: 2, + context_geometry: Geometry { + allocated_tokens: 8192, + max_tokens_per_sequence: 4096, + sequence_capacity: 4, + resident_minds: Minds { enabled: true, lanes: 2, parked_ids: 2, parked_free: 2, incarnation: 42 }, + }, + }; + let app = axum::Router::new() + .route("/props", axum::routing::get(move || { let props = props.clone(); async move { axum::Json(props) } })); + let namespace = format!("/{}", uuid::Uuid::new_v4()); // a recycled port is not this fixture engine + let app = axum::Router::new().nest(&namespace, app); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("test: bind"); + let root = format!("http://{}{namespace}", listener.local_addr().expect("test: addr")); + let server = tokio::spawn(async move { axum::serve(listener, app).await.expect("test: serve") }); + + let dir = tempfile::tempdir().expect("test: page dir"); + let endpoint = directory().endpoint(&root); + let contract = KvPageContract { + model_id: "fixture".into(), + model: "fixture.gguf".into(), + adapters: vec![], + page_dir: Some(dir.path().to_path_buf()), + context: 8192, + slots: 2, + cache_type: Some("q8_0".into()), + flash_attn: Some(true), + revisions: Some(vec![("fixture.gguf".into(), 73, std::time::SystemTime::UNIX_EPOCH)]), + }; + let transition = endpoint.transition().await; + let generation = transition.start_generation().expect("test: generation"); + transition.ready(&root, &generation, contract).expect("test: ready"); + drop(transition); + let owned = endpoint.admit().await.expect("test: ready pool").pool.expect("test: managed pool"); + assert_eq!(owned.resident_minds(), None, "the spawn knows its contract, not the engine's declaration"); + (root, owned, dir, server) +} + +const DECLARED: crate::inference::weight_residency::ResidentMinds = + crate::inference::weight_residency::ResidentMinds { lanes: 2, parked_ids: 2, incarnation: 42 }; + +// what this catches: the M5 2026-11-17 outage end to end (owned spawn -> adapter discovery -> admission). The +// owned pool must be accepted, record the engine's declaration and be admitted, and the fast path afterwards +// returns the same DECLARED pool. Before the fix every discovery here returned MindsMismatch. +#[tokio::test] +async fn an_owned_spawn_learns_its_engines_minds_at_discovery() { + let (root, owned, _dir, server) = owned_spawn_declaring_minds().await; + let client = reqwest::Client::new(); + let pool = directory().discover_pool(&client, &root).await.expect("discovery accepts the owned pool"); + assert!(Arc::ptr_eq(&pool, &owned), "the owned pool is the one discovered, not a replacement"); + assert_eq!(pool.resident_minds(), Some(DECLARED), "discovery recorded the engine's own declaration"); + assert!(directory().page_admission_known(&root), "page admission granted after the declaration"); + let again = directory().discover_pool(&client, &root).await.expect("the fast path"); + assert!(Arc::ptr_eq(&again, &owned) && again.resident_minds() == Some(DECLARED), "the fast path returns the declared pool"); + server.abort(); +} + +// what this catches: the lifecycle path granting page admission FIRST (a checkpoint before any adapter request) +// on an owned pool without the engine's minds declaration; the adapter's discovery then takes the fast path and +// would read the undeclared pool as core-paged minds (Codex on 5b2f48ae7). The lifecycle grant must declare. +#[tokio::test] +async fn a_lifecycle_admission_first_still_declares_the_engines_minds() { + let (root, owned, _dir, server) = owned_spawn_declaring_minds().await; + let client = reqwest::Client::new(); + directory().discover_page_admission(&client, &root).await.expect("the lifecycle path grants page admission"); + assert_eq!(owned.resident_minds(), Some(DECLARED), "the lifecycle grant recorded the engine's declaration"); + let pool = directory().discover_pool(&client, &root).await.expect("the adapter's fast path"); + assert!(Arc::ptr_eq(&pool, &owned), "the fast path returned the admitted owned pool"); + assert_eq!(pool.resident_minds(), Some(DECLARED), "never an undeclared pool read as core-paged minds"); + server.abort(); +} diff --git a/core/continuum-engine/src/inference/weight_residency.rs b/core/continuum-engine/src/inference/weight_residency.rs index 269e355355..5bfbd532c3 100644 --- a/core/continuum-engine/src/inference/weight_residency.rs +++ b/core/continuum-engine/src/inference/weight_residency.rs @@ -177,6 +177,36 @@ pub struct ContextGeometry { pub allocated_tokens: u64, pub max_tokens_per_sequence: u64, pub sequence_capacity: u64, + /// The engine keeps resident minds as parked sequences beside its lanes (fork #139): a mind switch is a + /// sequence move it owns. `None`: it does not (the core pages minds itself). Declared, never inferred. + pub resident_minds: Option, +} + +/// What an engine that owns mind switches reports: its lanes, the parked sequence ids beside them, and the token +/// it drew for this incarnation (a prefetch carries it back, so a replaced engine refuses a stream meant for another). +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +pub struct ResidentMinds { + pub lanes: u64, + pub parked_ids: u64, + pub incarnation: u64, +} + +/// `/props.context_geometry` as the fork writes it, decoded once. +#[derive(serde::Deserialize)] +struct GeometryWire { + allocated_tokens: u64, + max_tokens_per_sequence: u64, + sequence_capacity: u64, + #[serde(default)] + resident_minds: Option, +} + +/// `resident_minds`: with `enabled` false (no `--minds`) the rest means nothing. +#[derive(serde::Deserialize)] +struct MindsWire { + enabled: bool, + #[serde(flatten)] + minds: Option, } impl ContextGeometry { @@ -195,12 +225,18 @@ impl ContextGeometry { /// `None` when the engine reports no geometry (not our fork) or one that does not hold /// together: zero tokens, no sequence, or one sequence allowed more than the pool. pub fn from_props(props: &serde_json::Value) -> Option { - let geometry = props.get("context_geometry")?; - let read = |field: &str| geometry.get(field)?.as_u64(); + use serde::Deserialize as _; + let wire = GeometryWire::deserialize(props.get("context_geometry")?).ok()?; + let resident_minds = match wire.resident_minds { + Some(MindsWire { enabled: true, minds: Some(minds) }) => Some(minds), + Some(MindsWire { enabled: true, minds: None }) => return None, // declared but not whole: no geometry to trust + Some(MindsWire { enabled: false, .. }) | None => None, + }; let reported = Self { - allocated_tokens: read("allocated_tokens")?, - max_tokens_per_sequence: read("max_tokens_per_sequence")?, - sequence_capacity: read("sequence_capacity")?, + allocated_tokens: wire.allocated_tokens, + max_tokens_per_sequence: wire.max_tokens_per_sequence, + sequence_capacity: wire.sequence_capacity, + resident_minds, }; (reported.allocated_tokens > 0 && reported.sequence_capacity > 0 @@ -215,7 +251,12 @@ impl ContextGeometry { /// pool is larger (IntelMac 2026-11-03: n_ctx 32,768 beside 65,536; Cormac on #5722). fn allocated_capacity(props: &serde_json::Value, slots: u32, n_ctx_per_slot: u32) -> Option { let geometry = ContextGeometry::from_props(props)?; - (geometry.sequence_capacity == u64::from(slots) && u64::from(n_ctx_per_slot) <= geometry.max_tokens_per_sequence) + // an engine keeping resident minds holds its lanes AND their parked ids as sequences + let sequences = match geometry.resident_minds { + Some(minds) => u64::from(slots) + minds.parked_ids, + None => u64::from(slots), + }; + (geometry.sequence_capacity == sequences && u64::from(n_ctx_per_slot) <= geometry.max_tokens_per_sequence) .then_some(geometry.allocated_tokens) } diff --git a/core/continuum-serving/src/modules/serving_daemon/launch.rs b/core/continuum-serving/src/modules/serving_daemon/launch.rs index 66a58a0a0d..6b8ffa1faa 100644 --- a/core/continuum-serving/src/modules/serving_daemon/launch.rs +++ b/core/continuum-serving/src/modules/serving_daemon/launch.rs @@ -219,6 +219,10 @@ impl ServingDaemonModule { return None; } } + // the engine keeps every seated mind resident beside its lanes, plus one side sequence for learning + if let Some(minds) = u32::try_from(self.seated_needs(&model).len()).ok().and_then(|n| n.checked_add(1)).and_then(std::num::NonZeroU32::new) { + self.server.seat_minds(minds); + } let target = ServingTarget { host_prompt_cache_mib, model, diff --git a/core/continuum-serving/src/modules/serving_daemon/tests.rs b/core/continuum-serving/src/modules/serving_daemon/tests.rs index 94b80fbab8..af17fd6f73 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests.rs @@ -147,7 +147,7 @@ impl LlamaServerControl for FakeServer { } async fn served_geometry(&self) -> Result { // One sequence's worth of the fixed window above: the share these tests publish. - Ok(crate::inference::weight_residency::ContextGeometry { allocated_tokens: 11008, max_tokens_per_sequence: 11008, sequence_capacity: 1 }) + Ok(crate::inference::weight_residency::ContextGeometry { allocated_tokens: 11008, max_tokens_per_sequence: 11008, sequence_capacity: 1, resident_minds: None }) } async fn served_lanes(&self) -> Result { // 0 = "this fake's /props names no slot count", i.e. nothing to compare diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index 5f0a504f5f..6705f90528 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -f39cf25fbd3d95c69302fdf38d43dae2002b5f3e +945a742c3bc5b3e94845356b828e22422a53b52b diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index f39cf25fbd..945a742c3b 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit f39cf25fbd3d95c69302fdf38d43dae2002b5f3e +Subproject commit 945a742c3bc5b3e94845356b828e22422a53b52b