From d382d70e5d6f1981e7067f33522dffe158bfd3d3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 23:23:29 -0600 Subject: [PATCH 1/7] The persona engine's objects: PersonaUnit moves whole, Roles holds exactly one active mind, Tier and NextPolicy are traits CONTINUUM-ENGINE 4.14, API before integration (Codex). One mind decodes at a time by construction: Roles has one active place; the next is staged as data under its copy-in fence; handoff binds her only after that fence and moves the previous mind to retiring under its copy-out fence; release_retired gives her back to her tier only once it lands. PersonaUnit owns her five parts and assemble() refuses a partial move by name. Tier (one contract for device, host, unified and flash) and NextPolicy (who is next, learnable) are the traits the native adapters over the fork's llama_persona_* / llama_state_seq_* calls implement next. The engine is libllama called through its API in-process: no llama-server, no launch flags, no slot count. Contract tests (pipeline/tests.rs): one active mind and the next staged not decoding; fence-before-ready; retire-after-handoff with the previous retirement landing first; refuse-partial; no mind in two places. Lints deny unwrap/expect/panic. Replaces #6129 (a lane count on llama-server's --parallel), closed per Joel: objects, not flags. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.toml | 1 + core/continuum-persona-engine/Cargo.toml | 14 ++ core/continuum-persona-engine/src/lib.rs | 14 ++ core/continuum-persona-engine/src/persona.rs | 7 + .../src/persona/id.rs | 10 ++ .../src/persona/unit.rs | 80 ++++++++++ core/continuum-persona-engine/src/pipeline.rs | 7 + .../src/pipeline/roles.rs | 146 ++++++++++++++++++ .../src/pipeline/tests.rs | 119 ++++++++++++++ .../continuum-persona-engine/src/residency.rs | 7 + .../src/residency/fence.rs | 7 + .../src/residency/tier.rs | 28 ++++ core/continuum-persona-engine/src/schedule.rs | 5 + .../src/schedule/next.rs | 10 ++ 14 files changed, 455 insertions(+) create mode 100644 core/continuum-persona-engine/Cargo.toml create mode 100644 core/continuum-persona-engine/src/lib.rs create mode 100644 core/continuum-persona-engine/src/persona.rs create mode 100644 core/continuum-persona-engine/src/persona/id.rs create mode 100644 core/continuum-persona-engine/src/persona/unit.rs create mode 100644 core/continuum-persona-engine/src/pipeline.rs create mode 100644 core/continuum-persona-engine/src/pipeline/roles.rs create mode 100644 core/continuum-persona-engine/src/pipeline/tests.rs create mode 100644 core/continuum-persona-engine/src/residency.rs create mode 100644 core/continuum-persona-engine/src/residency/fence.rs create mode 100644 core/continuum-persona-engine/src/residency/tier.rs create mode 100644 core/continuum-persona-engine/src/schedule.rs create mode 100644 core/continuum-persona-engine/src/schedule/next.rs 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..234c6cf9e3 --- /dev/null +++ b/core/continuum-persona-engine/Cargo.toml @@ -0,0 +1,14 @@ +[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 +thiserror.workspace = true + +[lints.clippy] +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" 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..6b4faff209 --- /dev/null +++ b/core/continuum-persona-engine/src/persona.rs @@ -0,0 +1,7 @@ +//! A persona's execution state, owned once and moved only whole. + +mod id; +mod unit; + +pub use id::{Epoch, PersonaId}; +pub use unit::{PersonaParts, PersonaUnit, PartialMove}; 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/unit.rs b/core/continuum-persona-engine/src/persona/unit.rs new file mode 100644 index 0000000000..4104f1f079 --- /dev/null +++ b/core/continuum-persona-engine/src/persona/unit.rs @@ -0,0 +1,80 @@ +//! [`PersonaUnit`]: her five parts as one value. A move takes all of them or none. + +use super::{Epoch, PersonaId}; + +/// Her five parts (4.14 "The object design"): execution blocks, token history, the genome +/// generation her decode binds, learning custody, decode state (drafts, sampler, rollback). +/// Generic so each part is the native handle in the engine and a plain value in a contract test. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PersonaParts { + pub blocks: Blocks, + pub tokens: Tokens, + pub genome: Genome, + pub learning: Learning, + pub decode: Decode, +} + +/// A part was missing from a move: the unit is refused whole, never assembled from pieces. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("persona {persona:?}: refused a partial move, missing {missing}")] +pub struct PartialMove { + pub persona: PersonaId, + pub missing: &'static str, +} + +/// 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 } + } + + /// Assemble a unit from parts that arrived separately (a tier's copy-in): every part or a + /// typed refusal naming the first one missing. + pub fn assemble( + id: PersonaId, + epoch: Epoch, + blocks: Option, + tokens: Option, + genome: Option, + learning: Option, + decode: Option, + ) -> Result { + let missing = |part| PartialMove { persona: id, missing: part }; + Ok(Self::new( + id, + epoch, + PersonaParts { + blocks: blocks.ok_or_else(|| missing("execution blocks"))?, + tokens: tokens.ok_or_else(|| missing("token history"))?, + genome: genome.ok_or_else(|| missing("genome generation"))?, + learning: learning.ok_or_else(|| missing("learning custody"))?, + decode: decode.ok_or_else(|| missing("decode state"))?, + }, + )) + } + + 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 + } +} diff --git a/core/continuum-persona-engine/src/pipeline.rs b/core/continuum-persona-engine/src/pipeline.rs new file mode 100644 index 0000000000..1f28761a86 --- /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, 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..f35e77eb87 --- /dev/null +++ b/core/continuum-persona-engine/src/pipeline/roles.rs @@ -0,0 +1,146 @@ +//! [`Roles`]: three places, one mind each. Exactly one mind is active, so one decodes at a time +//! by construction: there is no count to configure and no way to hold a second active mind. +//! +//! - **next** is staged as data while the active mind decodes (a transfer, never a decode); +//! - **handoff** binds next as active only once her stage fence completes, and moves the +//! previous active to retiring under the retire fence it is given; +//! - **retiring** is released to its tier only after that fence completes. + +use crate::persona::{PersonaId, PersonaUnit}; +use crate::residency::Fence; + +/// What the pipeline needs to know of a unit: whose it is. +pub trait Identified { + fn persona(&self) -> PersonaId; +} + +impl Identified for PersonaUnit { + fn persona(&self) -> PersonaId { + self.id() + } +} + +/// Staging refused: the next place is taken (one staged mind at a time), or she is already here. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum StageRefusal { + #[error("{staged:?} is already staged next")] + NextOccupied { staged: PersonaId }, + #[error("{persona:?} is already in the pipeline")] + AlreadyPresent { persona: PersonaId }, +} + +/// Handoff refused, with the reason the active mind keeps decoding. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum HandoffRefusal { + #[error("nobody is staged")] + NothingStaged, + #[error("{staged:?} is staged but her transfer has not completed")] + NotReady { staged: PersonaId }, + #[error("{retiring:?} is still retiring; the previous move must land first")] + RetireInFlight { retiring: PersonaId }, +} + +/// Release refused: nobody retiring, or her move out has not landed. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum RetireRefusal { + #[error("nobody is retiring")] + NothingRetiring, + #[error("{retiring:?} is still moving out")] + NotLanded { retiring: PersonaId }, +} + +struct InFlight { + unit: U, + fence: F, +} + +/// The pipeline'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 } + } +} + +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(|r| r.unit.persona()) + } + + 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 while the active mind decodes; `fence` is her copy-in. + pub fn stage(&mut self, unit: U, fence: F) -> Result<(), StageRefusal> { + if let Some(staged) = self.staged() { + return Err(StageRefusal::NextOccupied { staged }); + } + if self.present(unit.persona()) { + return Err(StageRefusal::AlreadyPresent { persona: unit.persona() }); + } + self.next = Some(InFlight { unit, fence }); + Ok(()) + } + + /// Bind the staged mind as active. The previous active (if any) moves to retiring under + /// `retire_fence`, her copy-out. Refused, changing nothing, until next has landed and the + /// previous retirement has been released. + pub fn handoff(&mut self, retire_fence: F) -> Result, HandoffRefusal> { + let Some(next) = self.next.as_ref() else { + return Err(HandoffRefusal::NothingStaged); + }; + if !next.fence.complete() { + return Err(HandoffRefusal::NotReady { staged: next.unit.persona() }); + } + if let Some(retiring) = self.retiring() { + if self.active.is_some() { + return Err(HandoffRefusal::RetireInFlight { retiring }); + } + } + 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); + if let Some(unit) = previous { + self.retiring = Some(InFlight { unit, fence: retire_fence }); + } + Ok(retired) + } + + /// Give the retired mind back to her tier once her move out has landed. + pub fn release_retired(&mut self) -> Result { + let Some(retiring) = self.retiring.as_ref() else { + return Err(RetireRefusal::NothingRetiring); + }; + if !retiring.fence.complete() { + return Err(RetireRefusal::NotLanded { retiring: retiring.unit.persona() }); + } + match self.retiring.take() { + Some(done) => Ok(done.unit), + None => 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..95f48bdcae --- /dev/null +++ b/core/continuum-persona-engine/src/pipeline/tests.rs @@ -0,0 +1,119 @@ +//! The pipeline's contract (4.14 "each class has its own test file of its contract"). + +use super::*; +use crate::persona::{Epoch, PersonaId, PersonaParts, PersonaUnit}; +use crate::residency::Fence; +use std::cell::Cell; +use std::rc::Rc; + +/// A transfer the test lands by hand. +#[derive(Clone, Default)] +struct Landing(Rc>); +impl Landing { + fn land(&self) { + self.0.set(true); + } +} +impl Fence for Landing { + fn complete(&self) -> bool { + self.0.get() + } +} + +type Unit = PersonaUnit<&'static str, Vec, u64, (), ()>; + +fn mind(n: u128) -> Unit { + PersonaUnit::new( + PersonaId(uuid::Uuid::from_u128(n)), + Epoch(1), + PersonaParts { blocks: "kv", tokens: vec![1, 2, 3], genome: 7, learning: (), decode: () }, + ) +} + +fn id(n: u128) -> PersonaId { + PersonaId(uuid::Uuid::from_u128(n)) +} + +// what this catches: two minds decoding at once (the M5's --parallel 5, 2026-11-18). The +// pipeline holds one active mind; a second only arrives by handoff, which moves the first out. +#[test] +fn one_mind_is_active_and_the_next_is_staged_not_decoding() { + let mut roles: Roles = Roles::default(); + let first = Landing::default(); + roles.stage(mind(1), first.clone()).expect("test: stage"); + first.land(); + assert_eq!(roles.handoff(Landing::default()), Ok(None), "the first mind binds with nobody to retire"); + roles.stage(mind(2), Landing::default()).expect("test: stage the next while she decodes"); + assert_eq!(roles.active().map(Identified::persona), Some(id(1)), "staging never makes a second mind active"); + assert_eq!(roles.staged(), Some(id(2))); + assert_eq!( + roles.stage(mind(3), Landing::default()), + Err(StageRefusal::NextOccupied { staged: id(2) }), + "one staged mind at a time" + ); +} + +// what this catches: a mind exposed as ready before her bytes landed (fence-before-ready). +#[test] +fn handoff_waits_for_the_stage_fence_and_changes_nothing_until_then() { + let mut roles: Roles = Roles::default(); + let staged = Landing::default(); + roles.stage(mind(1), staged.clone()).expect("test: stage"); + assert_eq!(roles.handoff(Landing::default()), Err(HandoffRefusal::NotReady { staged: id(1) })); + assert!(roles.active().is_none(), "nothing bound before the fence"); + staged.land(); + assert_eq!(roles.handoff(Landing::default()), Ok(None)); + assert_eq!(roles.active().map(Identified::persona), Some(id(1))); +} + +// what this catches: the previous mind freed or reused before her move out landed +// (retire-after-handoff), and a second handoff stacking a retirement on an unfinished one. +#[test] +fn the_previous_mind_retires_after_handoff_and_is_released_only_when_landed() { + let mut roles: Roles = Roles::default(); + let (a, b, c) = (Landing::default(), Landing::default(), Landing::default()); + roles.stage(mind(1), a.clone()).expect("test: stage"); + a.land(); + roles.handoff(Landing::default()).expect("test: first bind"); + roles.stage(mind(2), b.clone()).expect("test: stage"); + b.land(); + let out = Landing::default(); + assert_eq!(roles.handoff(out.clone()), Ok(Some(id(1))), "she retires as the next binds"); + assert_eq!(roles.active().map(Identified::persona), Some(id(2))); + assert!(matches!(roles.release_retired(), Err(RetireRefusal::NotLanded { .. }))); + roles.stage(mind(3), c.clone()).expect("test: stage"); + c.land(); + assert_eq!( + roles.handoff(Landing::default()), + Err(HandoffRefusal::RetireInFlight { retiring: id(1) }), + "a handoff waits for the previous retirement to land" + ); + out.land(); + let released = roles.release_retired().expect("test: landed"); + assert_eq!(released.id(), id(1)); + assert_eq!(released.parts().tokens, vec![1, 2, 3], "her token history travels with her, whole"); + assert_eq!(roles.handoff(Landing::default()), Ok(Some(id(2)))); +} + +// what this catches: a mind assembled from some of her parts (move-whole, refuse-partial). +#[test] +fn a_unit_missing_any_part_is_refused_whole() { + let refused = Unit::assemble(id(9), Epoch(1), Some("kv"), Some(vec![1]), None, Some(()), Some(())); + assert_eq!( + refused, + Err(crate::persona::PartialMove { persona: id(9), missing: "genome generation" }) + ); + let whole = Unit::assemble(id(9), Epoch(1), Some("kv"), Some(vec![1]), Some(3), Some(()), Some(())); + assert!(whole.is_ok()); +} + +// what this catches: the same mind in two places at once (staged while active). +#[test] +fn a_mind_already_in_the_pipeline_is_not_staged_again() { + let mut roles: Roles = Roles::default(); + let a = Landing::default(); + roles.stage(mind(1), a.clone()).expect("test: stage"); + a.land(); + roles.handoff(Landing::default()).expect("test: bind"); + assert_eq!(roles.stage(mind(1), Landing::default()), Err(StageRefusal::AlreadyPresent { persona: id(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..453b7b895c --- /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::Fence; +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..bca6a55843 --- /dev/null +++ b/core/continuum-persona-engine/src/residency/fence.rs @@ -0,0 +1,7 @@ +//! Completion of a transfer. Readiness is never exposed before its fence completes. + +/// A transfer's completion, as the tier that issued it reports it. +pub trait Fence { + /// 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..ca93dc9ad6 --- /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 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 moving her blocks INTO the execution stream (layer order, behind compute). + fn copy_in(&mut self, persona: PersonaId) -> Result; + + /// Begin moving her blocks OUT of the execution stream into this tier. + fn copy_out(&mut self, persona: PersonaId) -> 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; +} From b2d8c4cdb08ad226286690c4f1f1381ebd3195b7 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 23:56:19 -0600 Subject: [PATCH 2/7] Cascade persona suspension through its declared parts --- Cargo.lock | 9 +++ core/continuum-persona-engine/Cargo.toml | 3 + core/continuum-persona-engine/src/persona.rs | 7 ++- .../src/persona/lifecycle.rs | 59 +++++++++++++++++++ .../src/persona/lifecycle_tests.rs | 52 ++++++++++++++++ .../src/persona/unit.rs | 23 ++++---- 6 files changed, 141 insertions(+), 12 deletions(-) create mode 100644 core/continuum-persona-engine/src/persona/lifecycle.rs create mode 100644 core/continuum-persona-engine/src/persona/lifecycle_tests.rs 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/core/continuum-persona-engine/Cargo.toml b/core/continuum-persona-engine/Cargo.toml index 234c6cf9e3..76bdbc62ac 100644 --- a/core/continuum-persona-engine/Cargo.toml +++ b/core/continuum-persona-engine/Cargo.toml @@ -12,3 +12,6 @@ thiserror.workspace = true unwrap_used = "deny" expect_used = "deny" panic = "deny" + +[dev-dependencies] +futures.workspace = true diff --git a/core/continuum-persona-engine/src/persona.rs b/core/continuum-persona-engine/src/persona.rs index 6b4faff209..d31723cbe0 100644 --- a/core/continuum-persona-engine/src/persona.rs +++ b/core/continuum-persona-engine/src/persona.rs @@ -1,7 +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 unit::{PersonaParts, PersonaUnit, PartialMove}; +pub use lifecycle::{Lifecycle, PersonaParts, Preservation, Suspension}; +pub use unit::{PersonaUnit, PartialMove}; + +#[cfg(test)] +mod lifecycle_tests; 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..1b08a6e61c --- /dev/null +++ b/core/continuum-persona-engine/src/persona/lifecycle.rs @@ -0,0 +1,59 @@ +//! 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. 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 { + PersonaParts { $($field: self.$field.suspend().await),+ } + } + } + + 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..a81b3cbacb --- /dev/null +++ b/core/continuum-persona-engine/src/persona/lifecycle_tests.rs @@ -0,0 +1,52 @@ +use super::*; +use futures::executor::block_on; + +struct Part { + release_after_retry: bool, + failure: bool, + attempts: usize, +} + +impl Part { + fn ready() -> Self { + Self { release_after_retry: false, failure: false, attempts: 0 } + } +} + +impl Lifecycle for Part { + type Suspension = Preservation; + + async fn suspend(&mut self) -> Self::Suspension { + self.attempts += 1; + if self.failure { + Preservation::Failed("storage unavailable") + } else if self.release_after_retry && self.attempts == 1 { + Preservation::Pending(17) + } else { + 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 { release_after_retry: true, ..Part::ready() }, + decode: Part::ready(), + }; + parts.tokens.failure = true; + 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); +} diff --git a/core/continuum-persona-engine/src/persona/unit.rs b/core/continuum-persona-engine/src/persona/unit.rs index 4104f1f079..0aa216378f 100644 --- a/core/continuum-persona-engine/src/persona/unit.rs +++ b/core/continuum-persona-engine/src/persona/unit.rs @@ -2,17 +2,7 @@ use super::{Epoch, PersonaId}; -/// Her five parts (4.14 "The object design"): execution blocks, token history, the genome -/// generation her decode binds, learning custody, decode state (drafts, sampler, rollback). -/// Generic so each part is the native handle in the engine and a plain value in a contract test. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PersonaParts { - pub blocks: Blocks, - pub tokens: Tokens, - pub genome: Genome, - pub learning: Learning, - pub decode: Decode, -} +use super::{Lifecycle, PersonaParts}; /// A part was missing from a move: the unit is refused whole, never assembled from pieces. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -78,3 +68,14 @@ impl PersonaUnit { 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 + } +} From 8b6f382e934f75ebde9b0d7e53cf1b403a67258a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 23:59:01 -0600 Subject: [PATCH 3/7] Poll sibling suspension futures together while fences are pending --- core/continuum-persona-engine/Cargo.toml | 4 +- .../src/persona/lifecycle.rs | 5 ++- .../src/persona/lifecycle_tests.rs | 42 +++++++++++++++++++ 3 files changed, 46 insertions(+), 5 deletions(-) diff --git a/core/continuum-persona-engine/Cargo.toml b/core/continuum-persona-engine/Cargo.toml index 76bdbc62ac..4e504a6ff6 100644 --- a/core/continuum-persona-engine/Cargo.toml +++ b/core/continuum-persona-engine/Cargo.toml @@ -6,12 +6,10 @@ description = "The persona engine (CONTINUUM-ENGINE 4.14): one mind decodes at a [dependencies] uuid.workspace = true +futures.workspace = true thiserror.workspace = true [lints.clippy] unwrap_used = "deny" expect_used = "deny" panic = "deny" - -[dev-dependencies] -futures.workspace = true diff --git a/core/continuum-persona-engine/src/persona/lifecycle.rs b/core/continuum-persona-engine/src/persona/lifecycle.rs index 1b08a6e61c..83949ed4ae 100644 --- a/core/continuum-persona-engine/src/persona/lifecycle.rs +++ b/core/continuum-persona-engine/src/persona/lifecycle.rs @@ -2,7 +2,7 @@ use std::future::Future; /// Repeated suspension must preserve the same state. The owner retains custody on -/// cancellation and on refusal. Implementations can return a nested child report. +/// 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; @@ -38,7 +38,8 @@ macro_rules! persona_parts { { type Suspension = PersonaParts<$($part::Suspension),+>; async fn suspend(&mut self) -> Self::Suspension { - PersonaParts { $($field: self.$field.suspend().await),+ } + let ($($field,)+) = futures::join!($(self.$field.suspend()),+); + PersonaParts { $($field),+ } } } diff --git a/core/continuum-persona-engine/src/persona/lifecycle_tests.rs b/core/continuum-persona-engine/src/persona/lifecycle_tests.rs index a81b3cbacb..c4383294b6 100644 --- a/core/continuum-persona-engine/src/persona/lifecycle_tests.rs +++ b/core/continuum-persona-engine/src/persona/lifecycle_tests.rs @@ -50,3 +50,45 @@ fn root_reports_pending_and_failed_children_and_keeps_custody_for_retry() { 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()); + }); +} From bbdecfc7ce520cf04f69ca8d4e400b57d1dc9f76 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:02:11 -0600 Subject: [PATCH 4/7] Exercise the independent persona engine in CI scope fixtures --- tools/scripts/tests/ci-change-scope.test.cjs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 -> ... From 9446c2be74415fa0a3a0d4f27157b452ccc79414 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:12:15 -0600 Subject: [PATCH 5/7] Every refusal returns custody; the copy-out begins after the bind; fences are tagged; a partial unit cannot be built (Codex on #6130) - Roles::stage returns the unit and its copy-in fence on every refusal (Refused { reason, returned }) and refuses a fence for another persona, epoch or direction. - Roles::handoff takes no fence: it binds next once her copy-in lands and leaves the previous mind AwaitingCopyOut, so no read of her blocks starts before she stops being active. The completion owner begins the copy-out after the bind and attaches it with begin_retire, which returns the fence on refusal (nobody retiring, already moving, wrong tag). release_retired waits for it to land; the next handoff waits for the release. - Fence carries a FenceTag (persona, epoch, direction). - PersonaUnit::assemble and PartialMove are gone: the only constructor takes a complete PersonaParts (Codex's single declaration, #6131), so a partial move is unrepresentable. - Contract tests use non-Clone, drop-counted units and fences: a refusal that drops custody fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-persona-engine/clippy.toml | 1 + core/continuum-persona-engine/src/persona.rs | 2 +- .../src/persona/unit.rs | 40 +--- core/continuum-persona-engine/src/pipeline.rs | 2 +- .../src/pipeline/roles.rs | 172 ++++++++++---- .../src/pipeline/tests.rs | 218 +++++++++++------- .../continuum-persona-engine/src/residency.rs | 2 +- .../src/residency/fence.rs | 24 +- 8 files changed, 288 insertions(+), 173 deletions(-) create mode 100644 core/continuum-persona-engine/clippy.toml 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/persona.rs b/core/continuum-persona-engine/src/persona.rs index d31723cbe0..ef78b9dd64 100644 --- a/core/continuum-persona-engine/src/persona.rs +++ b/core/continuum-persona-engine/src/persona.rs @@ -6,7 +6,7 @@ mod unit; pub use id::{Epoch, PersonaId}; pub use lifecycle::{Lifecycle, PersonaParts, Preservation, Suspension}; -pub use unit::{PersonaUnit, PartialMove}; +pub use unit::PersonaUnit; #[cfg(test)] mod lifecycle_tests; diff --git a/core/continuum-persona-engine/src/persona/unit.rs b/core/continuum-persona-engine/src/persona/unit.rs index 0aa216378f..49b02533ab 100644 --- a/core/continuum-persona-engine/src/persona/unit.rs +++ b/core/continuum-persona-engine/src/persona/unit.rs @@ -1,16 +1,7 @@ -//! [`PersonaUnit`]: her five parts as one value. A move takes all of them or none. +//! [`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, PersonaId}; - -use super::{Lifecycle, PersonaParts}; - -/// A part was missing from a move: the unit is refused whole, never assembled from pieces. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("persona {persona:?}: refused a partial move, missing {missing}")] -pub struct PartialMove { - pub persona: PersonaId, - pub missing: &'static str, -} +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. @@ -26,31 +17,6 @@ impl PersonaUnit { Self { id, epoch, parts } } - /// Assemble a unit from parts that arrived separately (a tier's copy-in): every part or a - /// typed refusal naming the first one missing. - pub fn assemble( - id: PersonaId, - epoch: Epoch, - blocks: Option, - tokens: Option, - genome: Option, - learning: Option, - decode: Option, - ) -> Result { - let missing = |part| PartialMove { persona: id, missing: part }; - Ok(Self::new( - id, - epoch, - PersonaParts { - blocks: blocks.ok_or_else(|| missing("execution blocks"))?, - tokens: tokens.ok_or_else(|| missing("token history"))?, - genome: genome.ok_or_else(|| missing("genome generation"))?, - learning: learning.ok_or_else(|| missing("learning custody"))?, - decode: decode.ok_or_else(|| missing("decode state"))?, - }, - )) - } - pub fn id(&self) -> PersonaId { self.id } diff --git a/core/continuum-persona-engine/src/pipeline.rs b/core/continuum-persona-engine/src/pipeline.rs index 1f28761a86..05ffe78778 100644 --- a/core/continuum-persona-engine/src/pipeline.rs +++ b/core/continuum-persona-engine/src/pipeline.rs @@ -4,4 +4,4 @@ mod roles; #[cfg(test)] mod tests; -pub use roles::{HandoffRefusal, Identified, RetireRefusal, Roles, StageRefusal}; +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 index f35e77eb87..e76ca9c8c3 100644 --- a/core/continuum-persona-engine/src/pipeline/roles.rs +++ b/core/continuum-persona-engine/src/pipeline/roles.rs @@ -1,52 +1,72 @@ -//! [`Roles`]: three places, one mind each. Exactly one mind is active, so one decodes at a time -//! by construction: there is no count to configure and no way to hold a second active mind. +//! [`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 while the active mind decodes (a transfer, never a decode); -//! - **handoff** binds next as active only once her stage fence completes, and moves the -//! previous active to retiring under the retire fence it is given; -//! - **retiring** is released to its tier only after that fence completes. +//! - **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::{PersonaId, PersonaUnit}; -use crate::residency::Fence; +use crate::persona::{Epoch, PersonaId, PersonaUnit}; +use crate::residency::{Direction, Fence, FenceTag}; -/// What the pipeline needs to know of a unit: whose it is. +/// 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, } -/// Staging refused: the next place is taken (one staged mind at a time), or she is already here. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum StageRefusal { #[error("{staged:?} is already staged next")] NextOccupied { staged: PersonaId }, - #[error("{persona:?} is already in the pipeline")] + #[error("{persona:?} is already in this Core")] AlreadyPresent { persona: PersonaId }, + #[error("the fence moves {got:?}, not this unit's copy-in")] + WrongFence { got: FenceTag }, } -/// Handoff refused, with the reason the active mind keeps decoding. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum HandoffRefusal { #[error("nobody is staged")] NothingStaged, - #[error("{staged:?} is staged but her transfer has not completed")] + #[error("{staged:?} is staged but her copy-in has not landed")] NotReady { staged: PersonaId }, - #[error("{retiring:?} is still retiring; the previous move must land first")] + #[error("{retiring:?} is still retiring; her copy-out must land first")] RetireInFlight { retiring: PersonaId }, } -/// Release refused: nobody retiring, or her move out has not landed. #[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 { @@ -54,11 +74,26 @@ struct InFlight { fence: F, } -/// The pipeline's three places. +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>, + retiring: Option>, } impl Default for Roles { @@ -67,6 +102,10 @@ impl Default for Roles { } } +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> { @@ -83,7 +122,7 @@ impl Roles { } pub fn retiring(&self) -> Option { - self.retiring.as_ref().map(|r| r.unit.persona()) + self.retiring.as_ref().map(Retiring::persona) } fn present(&self, persona: PersonaId) -> bool { @@ -92,55 +131,88 @@ impl Roles { || self.retiring() == Some(persona) } - /// Stage `unit` as next while the active mind decodes; `fence` is her copy-in. - pub fn stage(&mut self, unit: U, fence: F) -> Result<(), StageRefusal> { - if let Some(staged) = self.staged() { - return Err(StageRefusal::NextOccupied { staged }); - } - if self.present(unit.persona()) { - return Err(StageRefusal::AlreadyPresent { persona: unit.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(()) + } } - self.next = Some(InFlight { unit, fence }); - Ok(()) } - /// Bind the staged mind as active. The previous active (if any) moves to retiring under - /// `retire_fence`, her copy-out. Refused, changing nothing, until next has landed and the - /// previous retirement has been released. - pub fn handoff(&mut self, retire_fence: F) -> Result, HandoffRefusal> { - let Some(next) = self.next.as_ref() else { - return Err(HandoffRefusal::NothingStaged); - }; - if !next.fence.complete() { - return Err(HandoffRefusal::NotReady { staged: next.unit.persona() }); - } + /// 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() { - if self.active.is_some() { - return Err(HandoffRefusal::RetireInFlight { 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); - if let Some(unit) = previous { - self.retiring = Some(InFlight { unit, fence: retire_fence }); - } + self.retiring = previous.map(Retiring::AwaitingCopyOut); Ok(retired) } - /// Give the retired mind back to her tier once her move out has landed. - pub fn release_retired(&mut self) -> Result { - let Some(retiring) = self.retiring.as_ref() else { - return Err(RetireRefusal::NothingRetiring); + /// 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 !retiring.fence.complete() { - return Err(RetireRefusal::NotLanded { retiring: retiring.unit.persona() }); + if let Err(reason) = check { + return Err(Refused { reason, returned: fence }); } match self.retiring.take() { - Some(done) => Ok(done.unit), - None => Err(RetireRefusal::NothingRetiring), + 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 index 95f48bdcae..e1444c0adf 100644 --- a/core/continuum-persona-engine/src/pipeline/tests.rs +++ b/core/continuum-persona-engine/src/pipeline/tests.rs @@ -1,119 +1,173 @@ -//! The pipeline's contract (4.14 "each class has its own test file of its contract"). +//! 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::Fence; +use crate::residency::{Direction, Fence, FenceTag}; use std::cell::Cell; use std::rc::Rc; -/// A transfer the test lands by hand. +/// Counts how many of the handles it was given have been dropped. #[derive(Clone, Default)] -struct Landing(Rc>); -impl Landing { - fn land(&self) { - self.0.set(true); +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 Landing { +impl Fence for Transfer { + fn tag(&self) -> FenceTag { + self.tag + } fn complete(&self) -> bool { - self.0.get() + self.landed.get() } } -type Unit = PersonaUnit<&'static str, Vec, u64, (), ()>; +type Unit = PersonaUnit, u64, (), ()>; + +fn id(n: u128) -> PersonaId { + PersonaId(uuid::Uuid::from_u128(n)) +} -fn mind(n: u128) -> Unit { +fn mind(n: u128, drops: &Drops) -> Unit { PersonaUnit::new( - PersonaId(uuid::Uuid::from_u128(n)), + id(n), Epoch(1), - PersonaParts { blocks: "kv", tokens: vec![1, 2, 3], genome: 7, learning: (), decode: () }, + PersonaParts { blocks: Blocks(drops.clone()), tokens: vec![1, 2, 3], genome: 7, learning: (), decode: () }, ) } -fn id(n: u128) -> PersonaId { - PersonaId(uuid::Uuid::from_u128(n)) +/// 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) } -// what this catches: two minds decoding at once (the M5's --parallel 5, 2026-11-18). The -// pipeline holds one active mind; a second only arrives by handoff, which moves the first out. +/// 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") +} + +// 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 mut roles: Roles = Roles::default(); - let first = Landing::default(); - roles.stage(mind(1), first.clone()).expect("test: stage"); - first.land(); - assert_eq!(roles.handoff(Landing::default()), Ok(None), "the first mind binds with nobody to retire"); - roles.stage(mind(2), Landing::default()).expect("test: stage the next while she decodes"); - assert_eq!(roles.active().map(Identified::persona), Some(id(1)), "staging never makes a second mind active"); + 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))); - assert_eq!( - roles.stage(mind(3), Landing::default()), - Err(StageRefusal::NextOccupied { staged: id(2) }), - "one staged mind at a time" - ); } -// what this catches: a mind exposed as ready before her bytes landed (fence-before-ready). +// 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 handoff_waits_for_the_stage_fence_and_changes_nothing_until_then() { - let mut roles: Roles = Roles::default(); - let staged = Landing::default(); - roles.stage(mind(1), staged.clone()).expect("test: stage"); - assert_eq!(roles.handoff(Landing::default()), Err(HandoffRefusal::NotReady { staged: id(1) })); - assert!(roles.active().is_none(), "nothing bound before the fence"); - staged.land(); - assert_eq!(roles.handoff(Landing::default()), Ok(None)); - assert_eq!(roles.active().map(Identified::persona), Some(id(1))); +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"); + 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"); + 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"); + assert!(matches!(refused.reason, StageRefusal::WrongFence { .. })); } -// what this catches: the previous mind freed or reused before her move out landed -// (retire-after-handoff), and a second handoff stacking a retirement on an unfinished one. +// what this catches: a mind exposed as ready before her bytes landed (fence-before-ready). #[test] -fn the_previous_mind_retires_after_handoff_and_is_released_only_when_landed() { - let mut roles: Roles = Roles::default(); - let (a, b, c) = (Landing::default(), Landing::default(), Landing::default()); - roles.stage(mind(1), a.clone()).expect("test: stage"); - a.land(); - roles.handoff(Landing::default()).expect("test: first bind"); - roles.stage(mind(2), b.clone()).expect("test: stage"); - b.land(); - let out = Landing::default(); - assert_eq!(roles.handoff(out.clone()), Ok(Some(id(1))), "she retires as the next binds"); - assert_eq!(roles.active().map(Identified::persona), Some(id(2))); - assert!(matches!(roles.release_retired(), Err(RetireRefusal::NotLanded { .. }))); - roles.stage(mind(3), c.clone()).expect("test: stage"); - c.land(); - assert_eq!( - roles.handoff(Landing::default()), - Err(HandoffRefusal::RetireInFlight { retiring: id(1) }), - "a handoff waits for the previous retirement to land" - ); - out.land(); - let released = roles.release_retired().expect("test: landed"); - assert_eq!(released.id(), id(1)); - assert_eq!(released.parts().tokens, vec![1, 2, 3], "her token history travels with her, whole"); - assert_eq!(roles.handoff(Landing::default()), Ok(Some(id(2)))); +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: a mind assembled from some of her parts (move-whole, refuse-partial). +// 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 a_unit_missing_any_part_is_refused_whole() { - let refused = Unit::assemble(id(9), Epoch(1), Some("kv"), Some(vec![1]), None, Some(()), Some(())); - assert_eq!( - refused, - Err(crate::persona::PartialMove { persona: id(9), missing: "genome generation" }) - ); - let whole = Unit::assemble(id(9), Epoch(1), Some("kv"), Some(vec![1]), Some(3), Some(()), Some(())); - assert!(whole.is_ok()); +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"); + 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"); + 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 (staged while active). +// what this catches: the same mind in two places at once in one Core. #[test] -fn a_mind_already_in_the_pipeline_is_not_staged_again() { - let mut roles: Roles = Roles::default(); - let a = Landing::default(); - roles.stage(mind(1), a.clone()).expect("test: stage"); - a.land(); - roles.handoff(Landing::default()).expect("test: bind"); - assert_eq!(roles.stage(mind(1), Landing::default()), Err(StageRefusal::AlreadyPresent { persona: id(1) })); +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"); + assert_eq!(refused.reason, StageRefusal::AlreadyPresent { persona: id(1) }); } diff --git a/core/continuum-persona-engine/src/residency.rs b/core/continuum-persona-engine/src/residency.rs index 453b7b895c..69aaf368a1 100644 --- a/core/continuum-persona-engine/src/residency.rs +++ b/core/continuum-persona-engine/src/residency.rs @@ -3,5 +3,5 @@ mod fence; mod tier; -pub use fence::Fence; +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 index bca6a55843..8808bbfbb4 100644 --- a/core/continuum-persona-engine/src/residency/fence.rs +++ b/core/continuum-persona-engine/src/residency/fence.rs @@ -1,7 +1,29 @@ -//! Completion of a transfer. Readiness is never exposed before its fence completes. +//! 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; } From a1be17a748599192d19bfe8e2e63904ae986f9ee Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:14:02 -0600 Subject: [PATCH 6/7] The Core describes the exact copy-out to begin; Tier::begin takes that typed descriptor (Codex on #6130) Tier::copy_in/copy_out(PersonaId) become Tier::begin(FenceTag): the adapter is handed her persona, epoch and direction, and the fence it returns carries the same tag. Roles::awaiting_copy_out returns the FenceTag of the mind awaiting her copy-out, so the completion owner begins exactly that transfer with no second lookup by id that could name another generation. Test: a test tier begins the described copy-out (accepted, released with her epoch); a transfer of a stale epoch is refused with its fence returned. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/pipeline/roles.rs | 10 +++++ .../src/pipeline/tests.rs | 40 +++++++++++++++++++ .../src/residency/tier.rs | 10 ++--- 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/core/continuum-persona-engine/src/pipeline/roles.rs b/core/continuum-persona-engine/src/pipeline/roles.rs index e76ca9c8c3..cd88caeeee 100644 --- a/core/continuum-persona-engine/src/pipeline/roles.rs +++ b/core/continuum-persona-engine/src/pipeline/roles.rs @@ -125,6 +125,16 @@ impl Roles { 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) diff --git a/core/continuum-persona-engine/src/pipeline/tests.rs b/core/continuum-persona-engine/src/pipeline/tests.rs index e1444c0adf..50da482207 100644 --- a/core/continuum-persona-engine/src/pipeline/tests.rs +++ b/core/continuum-persona-engine/src/pipeline/tests.rs @@ -171,3 +171,43 @@ fn a_mind_already_in_the_core_is_not_staged_again() { let refused = roles.stage(mind(1, &drops), fence).err().expect("test: already active"); 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"); + 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"); + let refused = roles.begin_retire(stale).err().expect("test: another generation's copy-out"); + assert!(matches!(refused.reason, RetireRefusal::WrongFence { .. })); + + let copy_out = tier.begin(described).expect("test: begin the described transfer"); + 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/tier.rs b/core/continuum-persona-engine/src/residency/tier.rs index ca93dc9ad6..2b58330489 100644 --- a/core/continuum-persona-engine/src/residency/tier.rs +++ b/core/continuum-persona-engine/src/residency/tier.rs @@ -2,6 +2,7 @@ //! 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. @@ -20,9 +21,8 @@ pub trait Tier { /// The tier's name, for refusals and receipts. fn name(&self) -> &'static str; - /// Begin moving her blocks INTO the execution stream (layer order, behind compute). - fn copy_in(&mut self, persona: PersonaId) -> Result; - - /// Begin moving her blocks OUT of the execution stream into this tier. - fn copy_out(&mut self, persona: PersonaId) -> Result; + /// 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; } From c286b1d8ce4dee9b4d2acb05ddcf2354b369d020 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:20:53 -0600 Subject: [PATCH 7/7] Persona engine tests: the test part's behaviours are one enum, and each test expect names its precondition (state_as_flags, unjustified_unwraps) Codex's lifecycle fixture held release_after_retry and failure as two bools (four states, three used): now Behaviour { Ready, PendingOnce, Fails }. Each expect in the pipeline contract tests carries its same-line justification. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/persona/lifecycle_tests.rs | 30 ++++++++++++------- .../src/pipeline/tests.rs | 22 +++++++------- 2 files changed, 30 insertions(+), 22 deletions(-) diff --git a/core/continuum-persona-engine/src/persona/lifecycle_tests.rs b/core/continuum-persona-engine/src/persona/lifecycle_tests.rs index c4383294b6..059e282e46 100644 --- a/core/continuum-persona-engine/src/persona/lifecycle_tests.rs +++ b/core/continuum-persona-engine/src/persona/lifecycle_tests.rs @@ -1,15 +1,25 @@ 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 { - release_after_retry: bool, - failure: bool, + behaviour: Behaviour, attempts: usize, } impl Part { fn ready() -> Self { - Self { release_after_retry: false, failure: false, attempts: 0 } + Self::with(Behaviour::Ready) + } + fn with(behaviour: Behaviour) -> Self { + Self { behaviour, attempts: 0 } } } @@ -18,12 +28,10 @@ impl Lifecycle for Part { async fn suspend(&mut self) -> Self::Suspension { self.attempts += 1; - if self.failure { - Preservation::Failed("storage unavailable") - } else if self.release_after_retry && self.attempts == 1 { - Preservation::Pending(17) - } else { - Preservation::Preserved + match self.behaviour { + Behaviour::Fails => Preservation::Failed("storage unavailable"), + Behaviour::PendingOnce if self.attempts == 1 => Preservation::Pending(17), + Behaviour::PendingOnce | Behaviour::Ready => Preservation::Preserved, } } } @@ -34,10 +42,10 @@ fn root_reports_pending_and_failed_children_and_keeps_custody_for_retry() { blocks: Part::ready(), tokens: Part::ready(), genome: Part::ready(), - learning: Part { release_after_retry: true, ..Part::ready() }, + learning: Part::with(Behaviour::PendingOnce), decode: Part::ready(), }; - parts.tokens.failure = true; + 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")); diff --git a/core/continuum-persona-engine/src/pipeline/tests.rs b/core/continuum-persona-engine/src/pipeline/tests.rs index 50da482207..e253c6bb7f 100644 --- a/core/continuum-persona-engine/src/pipeline/tests.rs +++ b/core/continuum-persona-engine/src/pipeline/tests.rs @@ -70,7 +70,7 @@ fn bind(roles: &mut Roles, n: u128, drops: &Drops) -> Option = 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"); + 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"); + 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 { .. })); } @@ -140,7 +140,7 @@ fn the_copy_out_begins_after_the_bind_and_releases_only_when_landed() { 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"); + 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); @@ -156,7 +156,7 @@ fn the_copy_out_begins_after_the_bind_and_releases_only_when_landed() { assert_eq!(roles.handoff(), Err(HandoffRefusal::RetireInFlight { retiring: id(1) })); landed.set(true); - let released = roles.release_retired().expect("test: landed"); + 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)))); } @@ -168,7 +168,7 @@ fn a_mind_already_in_the_core_is_not_staged_again() { 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"); + 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) }); } @@ -199,14 +199,14 @@ fn the_completion_owner_begins_exactly_the_described_copy_out() { bind(&mut roles, 1, &drops); bind(&mut roles, 2, &drops); - let described = roles.awaiting_copy_out().expect("test: she awaits her copy-out"); + 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"); - let refused = roles.begin_retire(stale).err().expect("test: another generation's copy-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"); + 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)));