diff --git a/Cargo.lock b/Cargo.lock index 9343d5df25..91718e71e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3586,6 +3586,15 @@ dependencies = [ "uuid", ] +[[package]] +name = "continuum-persona-engine" +version = "0.1.0" +dependencies = [ + "futures", + "thiserror 2.0.18", + "uuid", +] + [[package]] name = "continuum-positron" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 779466f974..5431dfab2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ members = [ "core/continuum-core", "core/continuum-sentinel", "core/continuum-kernel", + "core/continuum-persona-engine", "core/continuum-store", "core/continuum-grid", "core/continuum-mind", diff --git a/core/continuum-persona-engine/Cargo.toml b/core/continuum-persona-engine/Cargo.toml new file mode 100644 index 0000000000..4e504a6ff6 --- /dev/null +++ b/core/continuum-persona-engine/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "continuum-persona-engine" +version = "0.1.0" +edition = "2021" +description = "The persona engine (CONTINUUM-ENGINE 4.14): one mind decodes at a time; the next is staged as data, the previous retires to RAM, a switch binds in ms. Objects, not launch flags." + +[dependencies] +uuid.workspace = true +futures.workspace = true +thiserror.workspace = true + +[lints.clippy] +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" diff --git a/core/continuum-persona-engine/clippy.toml b/core/continuum-persona-engine/clippy.toml new file mode 100644 index 0000000000..6933b81641 --- /dev/null +++ b/core/continuum-persona-engine/clippy.toml @@ -0,0 +1 @@ +allow-expect-in-tests = true diff --git a/core/continuum-persona-engine/src/lib.rs b/core/continuum-persona-engine/src/lib.rs new file mode 100644 index 0000000000..01ddc05d9f --- /dev/null +++ b/core/continuum-persona-engine/src/lib.rs @@ -0,0 +1,14 @@ +//! The persona engine (CONTINUUM-ENGINE 4.14): our loop over libllama, replacing +//! `llamacpp_scheduler`. ONE mind decodes at a time. The next is staged as data while she +//! decodes, the previous retires to the RAM tier after the handoff fence, and a switch binds +//! her blocks in milliseconds. Nothing here is a launch flag or a slot count: one-at-a-time is +//! the shape of [`pipeline::Roles`], which cannot hold two active minds. +//! +//! The engine is libllama in-process, called through its API (the fork's `llama_persona_*` and +//! `llama_state_seq_*` over `core/llama`): never a llama-server process configured by launch +//! flags. Each [`residency::Tier`] adapter wraps those calls; the pipeline decides when they run. + +pub mod persona; +pub mod pipeline; +pub mod residency; +pub mod schedule; diff --git a/core/continuum-persona-engine/src/persona.rs b/core/continuum-persona-engine/src/persona.rs new file mode 100644 index 0000000000..ef78b9dd64 --- /dev/null +++ b/core/continuum-persona-engine/src/persona.rs @@ -0,0 +1,12 @@ +//! A persona's execution state, owned once and moved only whole. + +mod id; +mod lifecycle; +mod unit; + +pub use id::{Epoch, PersonaId}; +pub use lifecycle::{Lifecycle, PersonaParts, Preservation, Suspension}; +pub use unit::PersonaUnit; + +#[cfg(test)] +mod lifecycle_tests; diff --git a/core/continuum-persona-engine/src/persona/id.rs b/core/continuum-persona-engine/src/persona/id.rs new file mode 100644 index 0000000000..20c9fddd2a --- /dev/null +++ b/core/continuum-persona-engine/src/persona/id.rs @@ -0,0 +1,10 @@ +//! Typed identities: a persona and the epoch her state belongs to. + +/// One persona, by her citizen id. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct PersonaId(pub uuid::Uuid); + +/// The generation of her state: a new epoch starts her blocks over (a new model, a revocation), +/// so state from another epoch is never bound as hers. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Epoch(pub u64); diff --git a/core/continuum-persona-engine/src/persona/lifecycle.rs b/core/continuum-persona-engine/src/persona/lifecycle.rs new file mode 100644 index 0000000000..83949ed4ae --- /dev/null +++ b/core/continuum-persona-engine/src/persona/lifecycle.rs @@ -0,0 +1,60 @@ +//! Each owner suspends its children and returns their preservation results. +use std::future::Future; + +/// Repeated suspension must preserve the same state. The owner retains custody on +/// cancellation and on refusal. A poll must yield promptly while I/O or GPU work is pending. Implementations can return a nested child report. +pub trait Lifecycle { + type Suspension: Suspension; + fn suspend(&mut self) -> impl Future + Send; +} + +pub trait Suspension { + fn is_preserved(&self) -> bool; +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Preservation { + Preserved, + Pending(P), + Failed(E), +} + +impl Suspension for Preservation { + fn is_preserved(&self) -> bool { + matches!(self, Self::Preserved) + } +} + +// One declaration supplies the owned fields, traversal, and typed report shape. +macro_rules! persona_parts { + ($($field:ident: $part:ident),+ $(,)?) => { + #[derive(Debug, Clone, PartialEq, Eq)] + pub struct PersonaParts<$($part),+> { + $(pub $field: $part),+ + } + + impl<$($part: Lifecycle + Send),+> Lifecycle for PersonaParts<$($part),+> + where $($part::Suspension: Send),+ + { + type Suspension = PersonaParts<$($part::Suspension),+>; + async fn suspend(&mut self) -> Self::Suspension { + let ($($field,)+) = futures::join!($(self.$field.suspend()),+); + PersonaParts { $($field),+ } + } + } + + impl<$($part: Suspension),+> Suspension for PersonaParts<$($part),+> { + fn is_preserved(&self) -> bool { + $(self.$field.is_preserved())&&+ + } + } + }; +} + +persona_parts! { + blocks: Blocks, + tokens: Tokens, + genome: Genome, + learning: Learning, + decode: Decode, +} diff --git a/core/continuum-persona-engine/src/persona/lifecycle_tests.rs b/core/continuum-persona-engine/src/persona/lifecycle_tests.rs new file mode 100644 index 0000000000..059e282e46 --- /dev/null +++ b/core/continuum-persona-engine/src/persona/lifecycle_tests.rs @@ -0,0 +1,102 @@ +use super::*; +use futures::executor::block_on; + +/// How a test part answers suspension: the three behaviours that exist, named (not two flags). +#[derive(Clone, Copy)] +enum Behaviour { + Ready, + PendingOnce, + Fails, +} + +struct Part { + behaviour: Behaviour, + attempts: usize, +} + +impl Part { + fn ready() -> Self { + Self::with(Behaviour::Ready) + } + fn with(behaviour: Behaviour) -> Self { + Self { behaviour, attempts: 0 } + } +} + +impl Lifecycle for Part { + type Suspension = Preservation; + + async fn suspend(&mut self) -> Self::Suspension { + self.attempts += 1; + match self.behaviour { + Behaviour::Fails => Preservation::Failed("storage unavailable"), + Behaviour::PendingOnce if self.attempts == 1 => Preservation::Pending(17), + Behaviour::PendingOnce | Behaviour::Ready => Preservation::Preserved, + } + } +} + +#[test] +fn root_reports_pending_and_failed_children_and_keeps_custody_for_retry() { + let mut parts = PersonaParts { + blocks: Part::ready(), + tokens: Part::ready(), + genome: Part::ready(), + learning: Part::with(Behaviour::PendingOnce), + decode: Part::ready(), + }; + parts.tokens.behaviour = Behaviour::Fails; + let mut persona = PersonaUnit::new(PersonaId(uuid::Uuid::nil()), Epoch(1), parts); + let report = block_on(persona.suspend()); + assert_eq!(report.tokens, Preservation::Failed("storage unavailable")); + assert_eq!(report.learning, Preservation::Pending(17)); + assert!(report.decode.is_preserved()); + assert!(!report.is_preserved()); + + let retried = block_on(persona.suspend()); + assert!(retried.learning.is_preserved()); + assert!(!retried.is_preserved()); + assert_eq!(persona.parts().learning.attempts, 2); +} + +#[test] +fn one_pending_fence_leaves_all_siblings_free_to_start() { + use futures::channel::oneshot; + use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; + + struct Gated { + started: Arc, + fence: oneshot::Receiver<()>, + } + impl Lifecycle for Gated { + type Suspension = Preservation<(), oneshot::Canceled>; + + async fn suspend(&mut self) -> Self::Suspension { + self.started.fetch_add(1, Ordering::SeqCst); + match (&mut self.fence).await { + Ok(()) => Preservation::Preserved, + Err(error) => Preservation::Failed(error), + } + } + } + + let started = Arc::new(AtomicUsize::new(0)); + let mut signals = Vec::new(); + let mut part = || { + let (signal, fence) = oneshot::channel(); + signals.push(signal); + Gated { started: started.clone(), fence } + }; + let mut persona = PersonaUnit::new(PersonaId(uuid::Uuid::nil()), Epoch(1), PersonaParts { + blocks: part(), tokens: part(), genome: part(), learning: part(), decode: part(), + }); + block_on(async { + let mut suspend = Box::pin(persona.suspend()); + assert!(futures::poll!(&mut suspend).is_pending()); + assert_eq!(started.load(Ordering::SeqCst), 5); + for signal in signals.into_iter().rev() { + assert!(signal.send(()).is_ok()); + } + assert!(suspend.await.is_preserved()); + }); +} diff --git a/core/continuum-persona-engine/src/persona/unit.rs b/core/continuum-persona-engine/src/persona/unit.rs new file mode 100644 index 0000000000..49b02533ab --- /dev/null +++ b/core/continuum-persona-engine/src/persona/unit.rs @@ -0,0 +1,47 @@ +//! [`PersonaUnit`]: her five parts as one value. A partial unit cannot be built: the only +//! constructor takes a complete [`PersonaParts`], so a move is whole by type. + +use super::{Epoch, Lifecycle, PersonaId, PersonaParts}; + +/// One persona's execution state. No part of her is held anywhere else: a slot's KV, a cycle's +/// gene set, a learner's pass are views of this unit, never copies. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PersonaUnit { + id: PersonaId, + epoch: Epoch, + parts: PersonaParts, +} + +impl PersonaUnit { + pub fn new(id: PersonaId, epoch: Epoch, parts: PersonaParts) -> Self { + Self { id, epoch, parts } + } + + pub fn id(&self) -> PersonaId { + self.id + } + + pub fn epoch(&self) -> Epoch { + self.epoch + } + + pub fn parts(&self) -> &PersonaParts { + &self.parts + } + + /// Give up the whole unit as its parts (a tier's copy-out takes all of them at once). + pub fn into_parts(self) -> PersonaParts { + self.parts + } +} + +impl Lifecycle for PersonaUnit +where + PersonaParts: Lifecycle + Send, +{ + type Suspension = as Lifecycle>::Suspension; + + async fn suspend(&mut self) -> Self::Suspension { + self.parts.suspend().await + } +} diff --git a/core/continuum-persona-engine/src/pipeline.rs b/core/continuum-persona-engine/src/pipeline.rs new file mode 100644 index 0000000000..05ffe78778 --- /dev/null +++ b/core/continuum-persona-engine/src/pipeline.rs @@ -0,0 +1,7 @@ +//! The active / next / retiring pipeline. + +mod roles; +#[cfg(test)] +mod tests; + +pub use roles::{HandoffRefusal, Identified, Refused, RetireRefusal, Roles, StageRefusal}; diff --git a/core/continuum-persona-engine/src/pipeline/roles.rs b/core/continuum-persona-engine/src/pipeline/roles.rs new file mode 100644 index 0000000000..cd88caeeee --- /dev/null +++ b/core/continuum-persona-engine/src/pipeline/roles.rs @@ -0,0 +1,228 @@ +//! [`Roles`]: one Core's three places, one mind each. Exactly one mind is active, so one decodes +//! at a time on this Core by construction (the engine owns the list of Cores and the measured +//! admission of another, CONTINUUM-ENGINE 4.14). +//! +//! - **next** is staged as data under her copy-in fence while the active mind decodes; +//! - **handoff** binds next once her fence lands and leaves the previous mind *awaiting copy-out*: +//! no read of her blocks starts before she has stopped being active; +//! - **begin_retire** attaches the copy-out the completion owner started after the bind; +//! - **release_retired** gives her back to her tier once that copy-out lands. +//! +//! Every refusal that receives owned values returns them ([`Refused`]): nothing is dropped. + +use crate::persona::{Epoch, PersonaId, PersonaUnit}; +use crate::residency::{Direction, Fence, FenceTag}; + +/// What the pipeline needs to know of a unit: whose it is and which generation. +pub trait Identified { + fn persona(&self) -> PersonaId; + fn epoch(&self) -> Epoch; +} + +impl Identified for PersonaUnit { + fn persona(&self) -> PersonaId { + self.id() + } + fn epoch(&self) -> Epoch { + PersonaUnit::epoch(self) + } +} + +/// A refusal that hands back everything it was given. +#[derive(Debug)] +pub struct Refused { + pub reason: R, + pub returned: V, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum StageRefusal { + #[error("{staged:?} is already staged next")] + NextOccupied { staged: PersonaId }, + #[error("{persona:?} is already in this Core")] + AlreadyPresent { persona: PersonaId }, + #[error("the fence moves {got:?}, not this unit's copy-in")] + WrongFence { got: FenceTag }, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum HandoffRefusal { + #[error("nobody is staged")] + NothingStaged, + #[error("{staged:?} is staged but her copy-in has not landed")] + NotReady { staged: PersonaId }, + #[error("{retiring:?} is still retiring; her copy-out must land first")] + RetireInFlight { retiring: PersonaId }, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum RetireRefusal { + #[error("nobody is retiring")] + NothingRetiring, + #[error("{retiring:?}'s copy-out was already begun")] + AlreadyMoving { retiring: PersonaId }, + #[error("{retiring:?} awaits a copy-out that has not begun")] + NotBegun { retiring: PersonaId }, + #[error("{retiring:?} is still moving out")] + NotLanded { retiring: PersonaId }, + #[error("the fence moves {got:?}, not this unit's copy-out")] + WrongFence { got: FenceTag }, +} + +struct InFlight { + unit: U, + fence: F, +} + +enum Retiring { + /// Bound out of active; no read of her blocks has begun. + AwaitingCopyOut(U), + Moving(InFlight), +} + +impl Retiring { + fn persona(&self) -> PersonaId { + match self { + Self::AwaitingCopyOut(unit) => unit.persona(), + Self::Moving(moving) => moving.unit.persona(), + } + } +} + +/// One Core's three places. +pub struct Roles { + active: Option, + next: Option>, + retiring: Option>, +} + +impl Default for Roles { + fn default() -> Self { + Self { active: None, next: None, retiring: None } + } +} + +fn expects(unit: &U, direction: Direction) -> FenceTag { + FenceTag { persona: unit.persona(), epoch: unit.epoch(), direction } +} + +impl Roles { + /// The mind decoding now. + pub fn active(&self) -> Option<&U> { + self.active.as_ref() + } + + /// Mutable access to the active mind only: decoding touches nobody else. + pub fn active_mut(&mut self) -> Option<&mut U> { + self.active.as_mut() + } + + pub fn staged(&self) -> Option { + self.next.as_ref().map(|n| n.unit.persona()) + } + + pub fn retiring(&self) -> Option { + self.retiring.as_ref().map(Retiring::persona) + } + + /// The exact copy-out to begin for the mind awaiting it (her persona, epoch, direction out): the + /// descriptor the completion owner hands its tier, so no second lookup by id can name another + /// generation. `None` when nobody awaits a copy-out. + pub fn awaiting_copy_out(&self) -> Option { + match self.retiring.as_ref() { + Some(Retiring::AwaitingCopyOut(unit)) => Some(expects(unit, Direction::Out)), + _ => None, + } + } + + fn present(&self, persona: PersonaId) -> bool { + self.active.as_ref().is_some_and(|a| a.persona() == persona) + || self.staged() == Some(persona) + || self.retiring() == Some(persona) + } + + /// Stage `unit` as next under `fence`, her copy-in. A refusal returns both. + pub fn stage(&mut self, unit: U, fence: F) -> Result<(), Refused> { + let reason = if let Some(staged) = self.staged() { + Some(StageRefusal::NextOccupied { staged }) + } else if self.present(unit.persona()) { + Some(StageRefusal::AlreadyPresent { persona: unit.persona() }) + } else if fence.tag() != expects(&unit, Direction::In) { + Some(StageRefusal::WrongFence { got: fence.tag() }) + } else { + None + }; + match reason { + Some(reason) => Err(Refused { reason, returned: (unit, fence) }), + None => { + self.next = Some(InFlight { unit, fence }); + Ok(()) + } + } + } + + /// Bind the staged mind as active once her copy-in has landed. The previous active mind (if + /// any) moves to retiring, awaiting the copy-out the completion owner begins after this + /// returns. Refused, changing nothing, until next has landed and the previous retirement is + /// released. + pub fn handoff(&mut self) -> Result, HandoffRefusal> { + if let Some(retiring) = self.retiring() { + return Err(HandoffRefusal::RetireInFlight { retiring }); + } + match self.next.as_ref() { + None => return Err(HandoffRefusal::NothingStaged), + Some(next) if !next.fence.complete() => { + return Err(HandoffRefusal::NotReady { staged: next.unit.persona() }) + } + Some(_) => {} + } + let Some(next) = self.next.take() else { + return Err(HandoffRefusal::NothingStaged); + }; + let previous = self.active.replace(next.unit); + let retired = previous.as_ref().map(Identified::persona); + self.retiring = previous.map(Retiring::AwaitingCopyOut); + Ok(retired) + } + + /// Attach the copy-out begun after the handoff. A refusal returns the fence. + pub fn begin_retire(&mut self, fence: F) -> Result<(), Refused> { + let check = match self.retiring.as_ref() { + None => Err(RetireRefusal::NothingRetiring), + Some(Retiring::Moving(moving)) => Err(RetireRefusal::AlreadyMoving { retiring: moving.unit.persona() }), + Some(Retiring::AwaitingCopyOut(unit)) if fence.tag() != expects(unit, Direction::Out) => { + Err(RetireRefusal::WrongFence { got: fence.tag() }) + } + Some(Retiring::AwaitingCopyOut(_)) => Ok(()), + }; + if let Err(reason) = check { + return Err(Refused { reason, returned: fence }); + } + match self.retiring.take() { + Some(Retiring::AwaitingCopyOut(unit)) => { + self.retiring = Some(Retiring::Moving(InFlight { unit, fence })); + Ok(()) + } + other => { + self.retiring = other; + Err(Refused { reason: RetireRefusal::NothingRetiring, returned: fence }) + } + } + } + + /// Give the retired mind back to her tier once her copy-out has landed. + pub fn release_retired(&mut self) -> Result { + match self.retiring.as_ref() { + None => return Err(RetireRefusal::NothingRetiring), + Some(Retiring::AwaitingCopyOut(unit)) => return Err(RetireRefusal::NotBegun { retiring: unit.persona() }), + Some(Retiring::Moving(moving)) if !moving.fence.complete() => { + return Err(RetireRefusal::NotLanded { retiring: moving.unit.persona() }) + } + Some(Retiring::Moving(_)) => {} + } + match self.retiring.take() { + Some(Retiring::Moving(done)) => Ok(done.unit), + _ => Err(RetireRefusal::NothingRetiring), + } + } +} diff --git a/core/continuum-persona-engine/src/pipeline/tests.rs b/core/continuum-persona-engine/src/pipeline/tests.rs new file mode 100644 index 0000000000..e253c6bb7f --- /dev/null +++ b/core/continuum-persona-engine/src/pipeline/tests.rs @@ -0,0 +1,213 @@ +//! The Core's contract (4.14: each class has a test file of its contract). Units and fences are +//! non-Clone handles that count their drops, so a refusal that loses custody fails here. + +use super::*; +use crate::persona::{Epoch, PersonaId, PersonaParts, PersonaUnit}; +use crate::residency::{Direction, Fence, FenceTag}; +use std::cell::Cell; +use std::rc::Rc; + +/// Counts how many of the handles it was given have been dropped. +#[derive(Clone, Default)] +struct Drops(Rc>); +impl Drops { + fn count(&self) -> u32 { + self.0.get() + } +} + +/// Her blocks: not Clone; dropping it is counted. +struct Blocks(Drops); +impl Drop for Blocks { + fn drop(&mut self) { + self.0 .0.set(self.0 .0.get() + 1); + } +} + +/// A transfer the test lands by hand; not Clone, dropping it is counted. +struct Transfer { + tag: FenceTag, + landed: Rc>, + drops: Drops, +} +impl Drop for Transfer { + fn drop(&mut self) { + self.drops.0.set(self.drops.0.get() + 1); + } +} +impl Fence for Transfer { + fn tag(&self) -> FenceTag { + self.tag + } + fn complete(&self) -> bool { + self.landed.get() + } +} + +type Unit = PersonaUnit, u64, (), ()>; + +fn id(n: u128) -> PersonaId { + PersonaId(uuid::Uuid::from_u128(n)) +} + +fn mind(n: u128, drops: &Drops) -> Unit { + PersonaUnit::new( + id(n), + Epoch(1), + PersonaParts { blocks: Blocks(drops.clone()), tokens: vec![1, 2, 3], genome: 7, learning: (), decode: () }, + ) +} + +/// A transfer for persona `n`, epoch 1, in `direction`, and the switch that lands it. +fn transfer(n: u128, direction: Direction, drops: &Drops) -> (Transfer, Rc>) { + let landed = Rc::new(Cell::new(false)); + let tag = FenceTag { persona: id(n), epoch: Epoch(1), direction }; + (Transfer { tag, landed: Rc::clone(&landed), drops: drops.clone() }, landed) +} + +/// Stage, land and bind persona `n` on `roles`. +fn bind(roles: &mut Roles, n: u128, drops: &Drops) -> Option { + let (fence, landed) = transfer(n, Direction::In, drops); + assert!(roles.stage(mind(n, drops), fence).is_ok(), "test: stage {n}"); + landed.set(true); + roles.handoff().expect("test: handoff") // expect: the test's own precondition +} + +// what this catches: two minds decoding at once (the M5's --parallel 5, 2026-11-18). A Core holds +// one active mind; staging the next never makes her active. +#[test] +fn one_mind_is_active_and_the_next_is_staged_not_decoding() { + let drops = Drops::default(); + let mut roles: Roles = Roles::default(); + assert_eq!(bind(&mut roles, 1, &drops), None); + let (fence, _landed) = transfer(2, Direction::In, &drops); + assert!(roles.stage(mind(2, &drops), fence).is_ok()); + assert_eq!(roles.active().map(Identified::persona), Some(id(1))); + assert_eq!(roles.staged(), Some(id(2))); +} + +// what this catches (Codex on #6130): a refused stage dropping the unit and its in-flight copy. +// Every refusal hands both back, and nothing is dropped by the pipeline. +#[test] +fn a_refused_stage_returns_the_unit_and_its_fence() { + let drops = Drops::default(); + let mut roles: Roles = Roles::default(); + let (fence, _l) = transfer(1, Direction::In, &drops); + assert!(roles.stage(mind(1, &drops), fence).is_ok()); + + let (fence, _l) = transfer(2, Direction::In, &drops); + let refused = roles.stage(mind(2, &drops), fence).err().expect("test: next is occupied"); // expect: the test's own precondition + assert_eq!(refused.reason, StageRefusal::NextOccupied { staged: id(1) }); + assert_eq!(drops.count(), 0, "nothing was dropped by the refusal"); + let (unit, fence) = refused.returned; + assert_eq!((unit.id(), fence.tag().persona), (id(2), id(2)), "custody came back whole"); + drop((unit, fence)); + assert_eq!(drops.count(), 2, "the caller, not the pipeline, released them"); + + let mut empty: Roles = Roles::default(); + let (wrong, _l) = transfer(9, Direction::In, &drops); + let refused = empty.stage(mind(3, &drops), wrong).err().expect("test: another persona's fence"); // expect: the test's own precondition + assert!(matches!(refused.reason, StageRefusal::WrongFence { .. })); + let (out, _l) = transfer(3, Direction::Out, &drops); + let (unit, _) = refused.returned; + let refused = empty.stage(unit, out).err().expect("test: a copy-out is not a copy-in"); // expect: the test's own precondition + assert!(matches!(refused.reason, StageRefusal::WrongFence { .. })); +} + +// what this catches: a mind exposed as ready before her bytes landed (fence-before-ready). +#[test] +fn handoff_waits_for_the_copy_in_and_changes_nothing_until_then() { + let drops = Drops::default(); + let mut roles: Roles = Roles::default(); + let (fence, landed) = transfer(1, Direction::In, &drops); + assert!(roles.stage(mind(1, &drops), fence).is_ok()); + assert_eq!(roles.handoff(), Err(HandoffRefusal::NotReady { staged: id(1) })); + assert!(roles.active().is_none()); + landed.set(true); + assert_eq!(roles.handoff(), Ok(None)); + assert_eq!(roles.active().map(Identified::persona), Some(id(1))); +} + +// what this catches (Codex on #6130): a copy-out started before the mind stopped being active. +// Handoff takes no fence: she leaves active first, then her copy-out is attached; the release +// waits for it to land, and the next handoff waits for the release. +#[test] +fn the_copy_out_begins_after_the_bind_and_releases_only_when_landed() { + let drops = Drops::default(); + let mut roles: Roles = Roles::default(); + bind(&mut roles, 1, &drops); + assert_eq!(bind(&mut roles, 2, &drops), Some(id(1)), "she leaves active as the next binds"); + assert_eq!(roles.release_retired().err(), Some(RetireRefusal::NotBegun { retiring: id(1) })); + + let (wrong, _l) = transfer(2, Direction::Out, &drops); + let refused = roles.begin_retire(wrong).err().expect("test: the active mind's copy-out is not hers"); // expect: the test's own precondition + assert!(matches!(refused.reason, RetireRefusal::WrongFence { .. })); + drop(refused.returned); + + let (out, landed) = transfer(1, Direction::Out, &drops); + assert!(roles.begin_retire(out).is_ok()); + let (again, _l) = transfer(1, Direction::Out, &drops); + assert!(matches!(roles.begin_retire(again).err().map(|r| r.reason), Some(RetireRefusal::AlreadyMoving { .. }))); + assert_eq!(roles.release_retired().err(), Some(RetireRefusal::NotLanded { retiring: id(1) })); + + let (fence, l3) = transfer(3, Direction::In, &drops); + assert!(roles.stage(mind(3, &drops), fence).is_ok()); + l3.set(true); + assert_eq!(roles.handoff(), Err(HandoffRefusal::RetireInFlight { retiring: id(1) })); + + landed.set(true); + let released = roles.release_retired().expect("test: landed"); // expect: the test's own precondition + assert_eq!((released.id(), released.parts().tokens.clone()), (id(1), vec![1, 2, 3]), "she travels whole"); + assert_eq!(roles.handoff(), Ok(Some(id(2)))); +} + +// what this catches: the same mind in two places at once in one Core. +#[test] +fn a_mind_already_in_the_core_is_not_staged_again() { + let drops = Drops::default(); + let mut roles: Roles = Roles::default(); + bind(&mut roles, 1, &drops); + let (fence, _l) = transfer(1, Direction::In, &drops); + let refused = roles.stage(mind(1, &drops), fence).err().expect("test: already active"); // expect: the test's own precondition + assert_eq!(refused.reason, StageRefusal::AlreadyPresent { persona: id(1) }); +} + +/// A tier that issues tagged transfers for whatever it is asked to begin. +struct TestTier { + drops: Drops, +} +impl crate::residency::Tier for TestTier { + type Fence = Transfer; + fn name(&self) -> &'static str { + "test" + } + fn begin(&mut self, what: FenceTag) -> Result { + Ok(Transfer { tag: what, landed: Rc::new(Cell::new(true)), drops: self.drops.clone() }) + } +} + +// what this catches (Codex on #6130 at 9446c2be7): the copy-out begun for a persona by id alone, +// which can name another generation of her. The completion owner begins exactly the transfer the +// Core describes, and a transfer of another epoch is refused with the fence returned. +#[test] +fn the_completion_owner_begins_exactly_the_described_copy_out() { + use crate::residency::Tier; + let drops = Drops::default(); + let mut tier = TestTier { drops: drops.clone() }; + let mut roles: Roles = Roles::default(); + assert_eq!(roles.awaiting_copy_out(), None, "nobody awaits a copy-out yet"); + bind(&mut roles, 1, &drops); + bind(&mut roles, 2, &drops); + + let described = roles.awaiting_copy_out().expect("test: she awaits her copy-out"); // expect: the test's own precondition + assert_eq!(described, FenceTag { persona: id(1), epoch: Epoch(1), direction: Direction::Out }); + + let stale = tier.begin(FenceTag { epoch: Epoch(0), ..described }).expect("test: the tier begins what it is told"); // expect: the test's own precondition + let refused = roles.begin_retire(stale).err().expect("test: another generation's copy-out"); // expect: the test's own precondition + assert!(matches!(refused.reason, RetireRefusal::WrongFence { .. })); + + let copy_out = tier.begin(described).expect("test: begin the described transfer"); // expect: the test's own precondition + assert!(roles.begin_retire(copy_out).is_ok()); + assert_eq!(roles.awaiting_copy_out(), None, "begun: no longer awaiting"); + assert_eq!(roles.release_retired().map(|u| u.epoch()), Ok(Epoch(1))); +} diff --git a/core/continuum-persona-engine/src/residency.rs b/core/continuum-persona-engine/src/residency.rs new file mode 100644 index 0000000000..69aaf368a1 --- /dev/null +++ b/core/continuum-persona-engine/src/residency.rs @@ -0,0 +1,7 @@ +//! Where a persona's bytes are: residency tiers behind one contract. + +mod fence; +mod tier; + +pub use fence::{Direction, Fence, FenceTag}; +pub use tier::{Tier, TierRefusal}; diff --git a/core/continuum-persona-engine/src/residency/fence.rs b/core/continuum-persona-engine/src/residency/fence.rs new file mode 100644 index 0000000000..8808bbfbb4 --- /dev/null +++ b/core/continuum-persona-engine/src/residency/fence.rs @@ -0,0 +1,29 @@ +//! Completion of a transfer, tied to what it moves. Readiness is never exposed before its fence +//! completes, and a fence for another persona, epoch or direction is never accepted. + +use crate::persona::{Epoch, PersonaId}; + +/// Which way a transfer moves her blocks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// Into the execution stream (staging her as next). + In, + /// Out of the execution stream to her tier (retiring her). + Out, +} + +/// What a fence moves: whose blocks, which generation of them, which way. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FenceTag { + pub persona: PersonaId, + pub epoch: Epoch, + pub direction: Direction, +} + +/// A transfer's completion, as the tier that issued it reports it. +pub trait Fence { + /// What this transfer moves. + fn tag(&self) -> FenceTag; + /// Whether every byte of the transfer has landed. + fn complete(&self) -> bool; +} diff --git a/core/continuum-persona-engine/src/residency/tier.rs b/core/continuum-persona-engine/src/residency/tier.rs new file mode 100644 index 0000000000..2b58330489 --- /dev/null +++ b/core/continuum-persona-engine/src/residency/tier.rs @@ -0,0 +1,28 @@ +//! [`Tier`]: one contract for every residency tier (device VRAM, pinned host RAM, the unified +//! pool, flash). An adapter holds only the calls that differ; the pipeline never branches on +//! which tier it has. + +use super::FenceTag; +use crate::persona::PersonaId; + +/// A tier could not take or give a persona's bytes: named, so the engine keeps her where she is. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{tier}: {reason} for persona {persona:?}")] +pub struct TierRefusal { + pub tier: &'static str, + pub persona: PersonaId, + pub reason: &'static str, +} + +/// A residency tier. +pub trait Tier { + type Fence: super::Fence; + + /// The tier's name, for refusals and receipts. + fn name(&self) -> &'static str; + + /// Begin the transfer `what` names: her blocks of that exact epoch, in that direction (into the + /// execution stream, layer order behind compute; or out of it into this tier). The fence it + /// returns carries the same tag, so [`crate::pipeline::Roles`] accepts it only for that unit. + fn begin(&mut self, what: FenceTag) -> Result; +} diff --git a/core/continuum-persona-engine/src/schedule.rs b/core/continuum-persona-engine/src/schedule.rs new file mode 100644 index 0000000000..6010d0d9eb --- /dev/null +++ b/core/continuum-persona-engine/src/schedule.rs @@ -0,0 +1,5 @@ +//! Who decodes next. + +mod next; + +pub use next::NextPolicy; diff --git a/core/continuum-persona-engine/src/schedule/next.rs b/core/continuum-persona-engine/src/schedule/next.rs new file mode 100644 index 0000000000..fdd0cec33a --- /dev/null +++ b/core/continuum-persona-engine/src/schedule/next.rs @@ -0,0 +1,10 @@ +//! [`NextPolicy`]: the choice of the next mind, pluggable and learnable (an algorithm behind a +//! trait, OpenCV-style), never a fixed rotation baked into the pipeline. + +use crate::persona::PersonaId; + +pub trait NextPolicy { + /// The mind to stage next from those waiting, given who is active now; `None` when nobody + /// should be staged yet. + fn choose(&mut self, waiting: &[PersonaId], active: Option) -> Option; +} diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index a17a3f6481..12d0cd6a73 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -12,7 +12,7 @@ const select = (...paths) => { // Tested crates a kernel change does not reach: the floor (base, host, git, service, saved-state) and // the leaves that depend on nothing in the workspace (the codec continuum-context, the flow // continuum-flow, the proving ground's types continuum-proving-types). -const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-saved-state', 'continuum-context', 'continuum-flow', 'continuum-proving-types']; +const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-saved-state', 'continuum-context', 'continuum-flow', 'continuum-proving-types', 'continuum-persona-engine']; test('installer repairs run installer checks without unrelated Rust builds', () => { for (const file of ['install.ps1', 'tools/scripts/lib/install-common.ps1', 'tools/scripts/lib/win-modules.ps1', 'tools/scripts/lib/win-engine.ps1', 'tools/scripts/lib/windows-engine-receipt.ps1', 'tools/scripts/lib/windows-service.ps1', 'tools/scripts/lib/windows-media-reconciliation.ps1', 'tools/scripts/lib/windows-elevation.ps1', 'tools/scripts/tests/windows-process.test.ps1', 'tools/scripts/tests/windows-airc-download.test.ps1', 'tools/scripts/tests/windows-xz.test.ps1', 'tools/scripts/sync-windows-bootstrap.ps1']) @@ -148,10 +148,11 @@ test('a crate-local change runs that crate and every crate that depends on it', const belowMind = crates('continuum-engine', 'continuum-vitals', 'continuum-prompt', 'continuum-engram', 'continuum-capture', 'continuum-embedding', 'continuum-store', 'continuum-models', 'continuum-hands', 'continuum-live', 'continuum-perception', 'continuum-genome', 'continuum-memory', 'continuum-cognition', 'continuum-academy', 'continuum-sentinel', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core', 'continuum-gateway'); assert.deepEqual(scope(['core/continuum-engine/src/lib.rs']), belowMind); // The floor crates (base, host, git) sit below the kernel: a kernel change runs everything above them. + assert.deepEqual(scope(['core/continuum-persona-engine/src/persona/unit.rs']), crates('continuum-persona-engine')); const aboveFloor = TESTED_CRATES.filter(n => !BELOW_KERNEL.includes(n)); assert.deepEqual(scope(['core/continuum-kernel/src/lib.rs']), { crates: aboveFloor, cli: false }); // A floor change runs the floor crate and every crate built on it. - assert.deepEqual(scope(['core/continuum-host/src/durable/mod.rs']), { crates: TESTED_CRATES.filter(n => !['continuum-base', 'continuum-service', 'continuum-context', 'continuum-flow', 'continuum-proving-types'].includes(n)), cli: true }); + assert.deepEqual(scope(['core/continuum-host/src/durable/mod.rs']), { crates: TESTED_CRATES.filter(n => !['continuum-base', 'continuum-service', 'continuum-context', 'continuum-flow', 'continuum-proving-types', 'continuum-persona-engine'].includes(n)), cli: true }); // continuum-git is used by hands (a citizen's git) and core (the deploy tree): both run, and every crate above hands. assert.deepEqual(scope(['core/continuum-git/src/index_lock.rs']), crates('continuum-git', 'continuum-hands', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); // Untested crates reach the tested ones through the graph: llama -> engine -> ...