From 2ef9f8e02b4f8c56d6ec90984211a7fd310a605c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:18:49 -0600 Subject: [PATCH 01/12] core/llama: a safe PersonaBlocks over the fork's persona seam; the engine pin moves to #147 (merged with the live engine) PersonaBlocks owns one llama_persona: new (blocks prepared for this context's memory), reserve (her token history, once, for a PersonaOwner), save (her state out of the context, raw), load (her blocks into an empty stream), owner (the stamp of the last save), tokens (her history in place), and Drop frees her. Every refusal is a typed PersonaRefusal carrying the fork's status name; the fork validates before writing, so a refusal leaves both sides as they were. The submodule moves from 5e4163402 (live) to 4caa55bf9: fork #147's head with 5e4163402 merged in, so the live engine's learn-abort fix (#150) is kept. Depends on fork #147 merging; draft until then. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/llama/Cargo.toml | 1 + core/llama/src/safe.rs | 2 + core/llama/src/safe/persona.rs | 99 ++++++++++++++++++++++++++++++++++ core/vendor/llama.cpp | 2 +- 4 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 core/llama/src/safe/persona.rs diff --git a/core/llama/Cargo.toml b/core/llama/Cargo.toml index 8210132fba..fc5bc778ad 100644 --- a/core/llama/Cargo.toml +++ b/core/llama/Cargo.toml @@ -11,6 +11,7 @@ name = "bench" path = "src/bin/bench.rs" [dependencies] +thiserror.workspace = true # Nothing yet — FFI + safe wrapper is self-contained [build-dependencies] diff --git a/core/llama/src/safe.rs b/core/llama/src/safe.rs index 0102f60cdc..c1ca4e8cfb 100644 --- a/core/llama/src/safe.rs +++ b/core/llama/src/safe.rs @@ -13,6 +13,8 @@ mod backend_init; pub use backend_init::*; mod expert_eval_cb; pub use expert_eval_cb::*; +mod persona; +pub use persona::{PersonaBlocks, PersonaOwner, PersonaRefusal}; // ─── Tests ─────────────────────────────────────────────────────────────── #[cfg(test)] diff --git a/core/llama/src/safe/persona.rs b/core/llama/src/safe/persona.rs new file mode 100644 index 0000000000..af0d2c9854 --- /dev/null +++ b/core/llama/src/safe/persona.rs @@ -0,0 +1,99 @@ +//! A persona's native blocks and token history (the fork's CONTINUUM-ENGINE 4.14 seam, +//! `llama_persona_*`): her state moves out of and back into the engine as raw copies, never +//! serialized, tokenized or re-prefilled, and only under the owner her token history was reserved +//! for. The persona engine's tier adapters call this; nothing here chooses when. + +use std::ptr::NonNull; + +use super::Context; +use crate::sys; + +/// Whose blocks these are: the persona and the epoch of her token history. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PersonaOwner { + pub persona: u64, + pub epoch: u64, +} + +/// A refusal from the fork, by its status name (`llama_persona_status_name`). Every refusal +/// leaves both sides as they were. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("persona move refused: {name}")] +pub struct PersonaRefusal { + pub status: i32, + pub name: String, +} + +fn status(code: i32) -> Result<(), PersonaRefusal> { + if code == 0 { + return Ok(()); + } + // SAFETY: the fork returns a static, NUL-terminated name for every status, unknown included. + let name = unsafe { std::ffi::CStr::from_ptr(sys::llama_persona_status_name(code)) } + .to_string_lossy() + .into_owned(); + Err(PersonaRefusal { status: code, name }) +} + +/// One persona's blocks and token history, owned once (freed with her). +pub struct PersonaBlocks { + ptr: NonNull, +} + +// The blocks are plain host memory owned by this handle; the engine owner moves them between +// threads only with the context they belong to. +unsafe impl Send for PersonaBlocks {} + +impl PersonaBlocks { + /// Empty blocks prepared for `ctx`'s memory; `None` when that memory has no persona move. + pub fn new(ctx: &mut Context<'_>) -> Option { + // SAFETY: `ctx` is a live context; the fork returns an owned persona or NULL. + NonNull::new(unsafe { sys::llama_persona_init(ctx.as_ptr()) }).map(|ptr| Self { ptr }) + } + + /// Reserve her token history once, for `owner`: `tokens` ids and `receipts` append receipts. + /// A second reserve is refused (`already_reserved`); an allocation failure is `out_of_memory`. + pub fn reserve(&mut self, owner: PersonaOwner, tokens: usize, receipts: usize) -> Result<(), PersonaRefusal> { + // SAFETY: `self.ptr` is live for this handle. + status(unsafe { sys::llama_persona_reserve_tokens(self.ptr.as_ptr(), owner.persona, owner.epoch, tokens, receipts) }) + } + + /// Move sequence `seq`'s state out of `ctx` into these blocks; her stream is left empty. + pub fn save(&mut self, ctx: &mut Context<'_>, seq: i32) -> Result<(), PersonaRefusal> { + // SAFETY: both pointers are live; the fork validates before writing and refuses whole. + status(unsafe { sys::llama_persona_save(ctx.as_ptr(), seq, self.ptr.as_ptr()) }) + } + + /// Bind these blocks into the empty `stream` of `ctx` as sequence `seq`. + pub fn load(&mut self, ctx: &mut Context<'_>, seq: i32, stream: u32) -> Result<(), PersonaRefusal> { + // SAFETY: both pointers are live; the fork validates before writing and refuses whole. + status(unsafe { sys::llama_persona_load(ctx.as_ptr(), seq, stream, self.ptr.as_ptr()) }) + } + + /// The owner stamped by the last completed save; `None` before one. + pub fn owner(&self) -> Option { + let (mut persona, mut epoch) = (0u64, 0u64); + // SAFETY: `self.ptr` is live; the out pointers are valid locals. + unsafe { sys::llama_persona_owner(self.ptr.as_ptr(), &mut persona, &mut epoch) } + .then_some(PersonaOwner { persona, epoch }) + } + + /// Her token history as held; empty before a reserve. + pub fn tokens(&self) -> &[i32] { + let mut n = 0u64; + // SAFETY: the fork returns her reserved buffer and its frontier (or NULL and 0); the + // buffer lives as long as this handle and only an append through `&mut self` changes it. + let ptr = unsafe { sys::llama_persona_token_ids(self.ptr.as_ptr(), &mut n) }; + match (NonNull::new(ptr as *mut i32), usize::try_from(n)) { + (Some(ptr), Ok(len)) => unsafe { std::slice::from_raw_parts(ptr.as_ptr(), len) }, + _ => &[], + } + } +} + +impl Drop for PersonaBlocks { + fn drop(&mut self) { + // SAFETY: owned since `new`; freed exactly once here. + unsafe { sys::llama_persona_free(self.ptr.as_ptr()) } + } +} diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 5e41634025..4caa55bf9c 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 5e4163402559c587b71cccc1ef67ea9a41a4a2ca +Subproject commit 4caa55bf9c11916d71d134a10089fbe9b77d1a60 From 998768ee50465b76ff503970e52a91ebb42cbde1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:21:18 -0600 Subject: [PATCH 02/12] Cargo.lock: core/llama depends on thiserror 2 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 9343d5df25..eadd60933e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7104,6 +7104,7 @@ dependencies = [ "cc", "cmake", "sha2", + "thiserror 2.0.18", ] [[package]] From 75a7710cd4f54fdb53fb15f09158745f60373a79 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:23:12 -0600 Subject: [PATCH 03/12] PersonaBlocks::bind replaces load(stream): the memory chooses the stream; pin fork #147 at bc9c9ae13 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/llama/src/safe/persona.rs | 7 ++++--- core/vendor/llama.cpp | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/core/llama/src/safe/persona.rs b/core/llama/src/safe/persona.rs index af0d2c9854..64b28c1a06 100644 --- a/core/llama/src/safe/persona.rs +++ b/core/llama/src/safe/persona.rs @@ -64,10 +64,11 @@ impl PersonaBlocks { status(unsafe { sys::llama_persona_save(ctx.as_ptr(), seq, self.ptr.as_ptr()) }) } - /// Bind these blocks into the empty `stream` of `ctx` as sequence `seq`. - pub fn load(&mut self, ctx: &mut Context<'_>, seq: i32, stream: u32) -> Result<(), PersonaRefusal> { + /// Bind these blocks into `ctx` as sequence `seq`, in an empty stream the memory chooses (the + /// caller never numbers streams); `no_empty_stream` when none is empty. + pub fn bind(&mut self, ctx: &mut Context<'_>, seq: i32) -> Result<(), PersonaRefusal> { // SAFETY: both pointers are live; the fork validates before writing and refuses whole. - status(unsafe { sys::llama_persona_load(ctx.as_ptr(), seq, stream, self.ptr.as_ptr()) }) + status(unsafe { sys::llama_persona_bind(ctx.as_ptr(), seq, self.ptr.as_ptr()) }) } /// The owner stamped by the last completed save; `None` before one. diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 4caa55bf9c..bc9c9ae13a 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 4caa55bf9c11916d71d134a10089fbe9b77d1a60 +Subproject commit bc9c9ae13adad70cb314999ce06cd08c89d56538 From c590d7ce664ea9951da87ac95b632e0dd124b0ff Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:26:38 -0600 Subject: [PATCH 04/12] LLAMA_CPP_PIN records the move to fork #147 (persona seam with bind), deliberately Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/vendor/LLAMA_CPP_PIN | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index 897ce00e0a..795a3869f8 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -5e4163402559c587b71cccc1ef67ea9a41a4a2ca +bc9c9ae13adad70cb314999ce06cd08c89d56538 From df3511545e6bb80f79800c26b1aa4c61b6add00c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:35:19 -0600 Subject: [PATCH 05/12] PersonaBlocks: reserve names only her owner, grow adds room ahead of need; pin fork #147 at 53609c556 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/llama/src/safe/persona.rs | 15 +++++++++++---- core/vendor/LLAMA_CPP_PIN | 2 +- core/vendor/llama.cpp | 2 +- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/core/llama/src/safe/persona.rs b/core/llama/src/safe/persona.rs index 64b28c1a06..580a823da5 100644 --- a/core/llama/src/safe/persona.rs +++ b/core/llama/src/safe/persona.rs @@ -51,11 +51,18 @@ impl PersonaBlocks { NonNull::new(unsafe { sys::llama_persona_init(ctx.as_ptr()) }).map(|ptr| Self { ptr }) } - /// Reserve her token history once, for `owner`: `tokens` ids and `receipts` append receipts. - /// A second reserve is refused (`already_reserved`); an allocation failure is `out_of_memory`. - pub fn reserve(&mut self, owner: PersonaOwner, tokens: usize, receipts: usize) -> Result<(), PersonaRefusal> { + /// Own her token history, once, for `owner`. Sized by nothing: it starts empty and her owner + /// grows it ahead of need ([`Self::grow`]). A second reserve is refused (`already_reserved`). + pub fn reserve(&mut self, owner: PersonaOwner) -> Result<(), PersonaRefusal> { // SAFETY: `self.ptr` is live for this handle. - status(unsafe { sys::llama_persona_reserve_tokens(self.ptr.as_ptr(), owner.persona, owner.epoch, tokens, receipts) }) + status(unsafe { sys::llama_persona_reserve_tokens(self.ptr.as_ptr(), owner.persona, owner.epoch) }) + } + + /// Grow her history by `tokens` ids and `receipts` appends, keeping what she holds. Her owner + /// calls it between acts, never inside one; an append on the hot path only writes. + pub fn grow(&mut self, tokens: usize, receipts: usize) -> Result<(), PersonaRefusal> { + // SAFETY: `self.ptr` is live for this handle. + status(unsafe { sys::llama_persona_grow_tokens(self.ptr.as_ptr(), tokens, receipts) }) } /// Move sequence `seq`'s state out of `ctx` into these blocks; her stream is left empty. diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index 795a3869f8..d7cdad3a9e 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -bc9c9ae13adad70cb314999ce06cd08c89d56538 +53609c55678992557537dbe724481ded84fddbb5 diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index bc9c9ae13a..53609c5567 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit bc9c9ae13adad70cb314999ce06cd08c89d56538 +Subproject commit 53609c55678992557537dbe724481ded84fddbb5 From ea955a81ae32fb43996608532dde7cba80d51871 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 01:06:18 -0600 Subject: [PATCH 06/12] PersonaBlocks is made with her owner and grows and shrinks; pin fork 37baf8c12 Joel: "we don't reserve. We literally do the opposite. We grow and shrink." - PersonaBlocks::new(ctx, owner) makes her owned from the start; reserve is gone. - shrink() beside grow(): gives back the room she does not hold as she cools, dropping nothing. - Fork 37baf8c12: llama_persona_init(ctx, persona, epoch), llama_persona_shrink_tokens, and ownership enforced in the native save/load/bind (one check, no path skips it). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/llama/src/safe/persona.rs | 30 +++++++++++++++--------------- core/vendor/LLAMA_CPP_PIN | 2 +- core/vendor/llama.cpp | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/core/llama/src/safe/persona.rs b/core/llama/src/safe/persona.rs index 580a823da5..46a81d5a27 100644 --- a/core/llama/src/safe/persona.rs +++ b/core/llama/src/safe/persona.rs @@ -1,7 +1,7 @@ //! A persona's native blocks and token history (the fork's CONTINUUM-ENGINE 4.14 seam, //! `llama_persona_*`): her state moves out of and back into the engine as raw copies, never -//! serialized, tokenized or re-prefilled, and only under the owner her token history was reserved -//! for. The persona engine's tier adapters call this; nothing here chooses when. +//! serialized, tokenized or re-prefilled, and only under the owner she was made for (the native save +//! stamps it, the native load and bind refuse anyone else). The persona engine's tier adapters call this; nothing here chooses when. use std::ptr::NonNull; @@ -45,26 +45,26 @@ pub struct PersonaBlocks { unsafe impl Send for PersonaBlocks {} impl PersonaBlocks { - /// Empty blocks prepared for `ctx`'s memory; `None` when that memory has no persona move. - pub fn new(ctx: &mut Context<'_>) -> Option { + /// One persona for `ctx`'s memory, made for `owner`: her blocks empty, her token history empty and + /// sized by nothing. `None` when that memory has no persona move. + pub fn new(ctx: &mut Context<'_>, owner: PersonaOwner) -> Option { // SAFETY: `ctx` is a live context; the fork returns an owned persona or NULL. - NonNull::new(unsafe { sys::llama_persona_init(ctx.as_ptr()) }).map(|ptr| Self { ptr }) - } - - /// Own her token history, once, for `owner`. Sized by nothing: it starts empty and her owner - /// grows it ahead of need ([`Self::grow`]). A second reserve is refused (`already_reserved`). - pub fn reserve(&mut self, owner: PersonaOwner) -> Result<(), PersonaRefusal> { - // SAFETY: `self.ptr` is live for this handle. - status(unsafe { sys::llama_persona_reserve_tokens(self.ptr.as_ptr(), owner.persona, owner.epoch) }) + NonNull::new(unsafe { sys::llama_persona_init(ctx.as_ptr(), owner.persona, owner.epoch) }).map(|ptr| Self { ptr }) } /// Grow her history by `tokens` ids and `receipts` appends, keeping what she holds. Her owner - /// calls it between acts, never inside one; an append on the hot path only writes. + /// calls it ahead of need, between acts, never inside one; an append on the hot path only writes. pub fn grow(&mut self, tokens: usize, receipts: usize) -> Result<(), PersonaRefusal> { // SAFETY: `self.ptr` is live for this handle. status(unsafe { sys::llama_persona_grow_tokens(self.ptr.as_ptr(), tokens, receipts) }) } + /// Give back the room she does not hold as she cools; nothing she holds is dropped. + pub fn shrink(&mut self) -> Result<(), PersonaRefusal> { + // SAFETY: `self.ptr` is live for this handle. + status(unsafe { sys::llama_persona_shrink_tokens(self.ptr.as_ptr()) }) + } + /// Move sequence `seq`'s state out of `ctx` into these blocks; her stream is left empty. pub fn save(&mut self, ctx: &mut Context<'_>, seq: i32) -> Result<(), PersonaRefusal> { // SAFETY: both pointers are live; the fork validates before writing and refuses whole. @@ -86,10 +86,10 @@ impl PersonaBlocks { .then_some(PersonaOwner { persona, epoch }) } - /// Her token history as held; empty before a reserve. + /// Her token history as held; empty until her first append. pub fn tokens(&self) -> &[i32] { let mut n = 0u64; - // SAFETY: the fork returns her reserved buffer and its frontier (or NULL and 0); the + // SAFETY: the fork returns her history's buffer and its frontier (or NULL and 0); the // buffer lives as long as this handle and only an append through `&mut self` changes it. let ptr = unsafe { sys::llama_persona_token_ids(self.ptr.as_ptr(), &mut n) }; match (NonNull::new(ptr as *mut i32), usize::try_from(n)) { diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index d7cdad3a9e..c9106fca66 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -53609c55678992557537dbe724481ded84fddbb5 +37baf8c120e3455ec9ea9d81015b7c8bb60391d4 diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 53609c5567..37baf8c120 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 53609c55678992557537dbe724481ded84fddbb5 +Subproject commit 37baf8c120e3455ec9ea9d81015b7c8bb60391d4 From 3d16663e25cb2ba519c32a79771fd9498d525d48 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 01:38:08 -0600 Subject: [PATCH 07/12] The persona engine switches minds on the real 35B in ~9 ms: UnifiedTier over the fork's native blocks continuum-persona-llama: the persona engine's residency Tier on one libllama context. Two execution streams: the active mind decodes in one while the next binds into the other; every other mind's blocks stay in RAM exactly as she left them. A move out is the fork's native save, a move in its native bind; both are synchronous, so the fence has landed when it exists. Each persona gets an exact 64-bit owner stamp from this tier (a persona is 128 bits; the fork stamps 64). Fork a88f255cc: a mind binds as whichever sequence she is bound as (her cells are relabeled), so two streams serve any number of minds. examples/persona_switch drives N minds through Roles (stage, handoff, copy-out, release) on a real model. ## Measured (M5, Qwen3.6-35B-A3B Q4_K_M, serving down 07:32-07:37Z, fork a88f255cc) 4,096-token history per mind, 64 decoded tokens per turn, 3 rounds: - 4 minds: switch p50 8.83 ms, p90 10.76 ms; decode 54.7 tok/s; sustained incl. switches 54.3 tok/s - 8 minds: switch p50 8.36 ms, p90 9.82 ms; decode 55.7 tok/s; sustained 55.3 tok/s - 16 minds: switch p50 8.59 ms, p90 10.06 ms; decode 55.3 tok/s; sustained 54.9 tok/s Live serving the same morning: KV page saves 8.7-13.1 s. Switching now costs under 1% of decode. Not yet at the 80 tok/s gate: this harness decodes one greedy token per step with no MTP draft; the live engine's 80 comes with the draft model, which the persona engine has to drive next. Fork tests at a88f255cc: 6/6 persona tests passed, including a saved-as-0, bound-as-1 continuation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.lock | 10 ++ Cargo.toml | 1 + core/continuum-persona-llama/Cargo.toml | 19 +++ .../examples/persona_switch.rs | 137 ++++++++++++++++ core/continuum-persona-llama/src/lib.rs | 9 + .../src/unified_tier.rs | 155 ++++++++++++++++++ core/vendor/LLAMA_CPP_PIN | 2 +- core/vendor/llama.cpp | 2 +- 8 files changed, 333 insertions(+), 2 deletions(-) create mode 100644 core/continuum-persona-llama/Cargo.toml create mode 100644 core/continuum-persona-llama/examples/persona_switch.rs create mode 100644 core/continuum-persona-llama/src/lib.rs create mode 100644 core/continuum-persona-llama/src/unified_tier.rs diff --git a/Cargo.lock b/Cargo.lock index 9f29ef2e3a..a26ed6fe52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3595,6 +3595,16 @@ dependencies = [ "uuid", ] +[[package]] +name = "continuum-persona-llama" +version = "0.1.0" +dependencies = [ + "continuum-persona-engine", + "llama", + "thiserror 2.0.18", + "uuid", +] + [[package]] name = "continuum-positron" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 5431dfab2c..564ac48d22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ members = [ "core/continuum-sentinel", "core/continuum-kernel", "core/continuum-persona-engine", + "core/continuum-persona-llama", "core/continuum-store", "core/continuum-grid", "core/continuum-mind", diff --git a/core/continuum-persona-llama/Cargo.toml b/core/continuum-persona-llama/Cargo.toml new file mode 100644 index 0000000000..07a228ae4c --- /dev/null +++ b/core/continuum-persona-llama/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "continuum-persona-llama" +version = "0.1.0" +edition = "2021" +description = "The persona engine's residency tier over the fork's native persona blocks (CONTINUUM-ENGINE 4.14): one context, two execution streams (the active mind decodes in one while the next binds into the other), every other mind's blocks in RAM. A switch is a native bind, never a serialize or a re-prefill." + +[features] +metal = ["llama/metal"] + +[dependencies] +continuum-persona-engine = { path = "../continuum-persona-engine" } +llama = { path = "../llama" } +thiserror.workspace = true +uuid.workspace = true + +[lints.clippy] +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" diff --git a/core/continuum-persona-llama/examples/persona_switch.rs b/core/continuum-persona-llama/examples/persona_switch.rs new file mode 100644 index 0000000000..364194f02d --- /dev/null +++ b/core/continuum-persona-llama/examples/persona_switch.rs @@ -0,0 +1,137 @@ +//! The persona engine on a real model: N minds take turns through `Roles` and the `UnifiedTier`, one +//! decoding at a time. Each turn stages the next mind (her copy-in), hands off, retires the previous +//! mind (her copy-out to RAM), then decodes. Reports the switch (handoff + copy-out + copy-in) and the +//! decode rate, separately and together. +//! +//! cargo run --release --features metal --example persona_switch -- + +use std::time::{Duration, Instant}; + +use continuum_persona_engine::persona::{Epoch, PersonaId}; +use continuum_persona_engine::pipeline::{Identified, Roles}; +use continuum_persona_engine::residency::{Direction, FenceTag, Tier}; +use continuum_persona_llama::{Landed, UnifiedTier}; +use llama::{Batch, ContextParams, FlashAttn, Model, ModelParams}; + +/// One mind in the run: who she is, where her history ends, and her last sampled token. +struct Mind { + id: PersonaId, + epoch: Epoch, + prompt: Vec, + pos: i32, + last: i32, +} + +impl Identified for Mind { + fn persona(&self) -> PersonaId { + self.id + } + fn epoch(&self) -> Epoch { + self.epoch + } +} + +fn argmax(logits: &[f32]) -> i32 { + let mut best = (0usize, f32::MIN); + for (i, &v) in logits.iter().enumerate() { + if v > best.1 { + best = (i, v); + } + } + best.0 as i32 +} + +fn arg(args: &[String], i: usize, what: &str) -> Result { + args.get(i).ok_or(format!("missing {what}"))?.parse().map_err(|e| format!("{what}: {e}")) +} + +fn main() -> Result<(), String> { + let args: Vec = std::env::args().collect(); + let model_path = args.get(1).ok_or("usage: persona_switch ")?; + let (minds, prompt_tokens, decode_tokens, rounds) = + (arg(&args, 2, "minds")?, arg(&args, 3, "prompt_tokens")?, arg(&args, 4, "decode_tokens")?, arg(&args, 5, "rounds")?); + + llama::backend_init(); + let model = Model::load(model_path, ModelParams::default())?; + // two execution streams (active + next); each holds one mind's whole window + let window = (prompt_tokens + decode_tokens * rounds + 64) as u32; + let params = ContextParams { n_ctx: window * 2, n_batch: 2048, n_ubatch: 2048, n_seq_max: 2, flash_attn: FlashAttn::Enabled, ..ContextParams::default() }; + let mut ctx = model.new_context(params)?; + let mut tier = UnifiedTier::new(&mut ctx); + + let mut parked: Vec = (0..minds) + .map(|i| { + let text = format!("Mind {i} keeps her own notes. ").repeat(prompt_tokens / 6 + 1); + let mut prompt = model.tokenize(&text, true, false)?; + prompt.truncate(prompt_tokens); + Ok(Mind { id: PersonaId(uuid::Uuid::new_v4()), epoch: Epoch(1), prompt, pos: 0, last: 0 }) + }) + .collect::>()?; + + let mut roles: Roles = Roles::default(); + let (mut switches, mut decode_time, mut decoded, mut prefill_time) = (Vec::new(), Duration::ZERO, 0usize, Duration::ZERO); + let run = Instant::now(); + for turn in 0..minds * rounds { + // the next mind in turn order (the scheduler's choice in the engine; round-robin here) + let next = parked.remove(0); + let t = Instant::now(); + let fence = tier.begin(FenceTag { persona: next.id, epoch: next.epoch, direction: Direction::In }).map_err(|e| e.to_string())?; + roles.stage(next, fence).map_err(|r| format!("{:?}", r.reason))?; + roles.handoff().map_err(|e| format!("{e:?}"))?; + if let Some(out) = roles.awaiting_copy_out() { + let fence = tier.begin(out).map_err(|e| e.to_string())?; + roles.begin_retire(fence).map_err(|r| format!("{:?}", r.reason))?; + parked.push(roles.release_retired().map_err(|e| format!("{e:?}"))?); + } + let switched = t.elapsed(); + if turn > 0 { + switches.push(switched); + } + + let mind = roles.active_mut().ok_or("no active mind after handoff")?; + let seq = tier.stream_of(mind.id).ok_or("the active mind is not bound")?.seq(); + let ctx = tier.context(); + if mind.pos == 0 { + let t = Instant::now(); + let mut last_index = 0; + for chunk in mind.prompt.chunks(2048) { + let mut batch = Batch::allocated(chunk.len() as i32, 1); + for (j, &tok) in chunk.iter().enumerate() { + batch.push(tok, mind.pos + j as i32, &[seq], j + 1 == chunk.len()); + } + ctx.decode(&batch)?; + mind.pos += chunk.len() as i32; + last_index = chunk.len() as i32 - 1; + } + mind.last = argmax(ctx.logits_ith(last_index)); + prefill_time += t.elapsed(); + } + let t = Instant::now(); + for _ in 0..decode_tokens { + let mut batch = Batch::allocated(1, 1); + batch.push(mind.last, mind.pos, &[seq], true); + ctx.decode(&batch)?; + mind.pos += 1; + mind.last = argmax(ctx.logits_ith(0)); + } + decode_time += t.elapsed(); + decoded += decode_tokens; + } + + switches.sort(); + let ms = |d: Duration| d.as_secs_f64() * 1e3; + let p = |q: f64| switches.get(((switches.len() as f64 - 1.0) * q) as usize).copied().map(ms).unwrap_or(0.0); + let decode_tps = decoded as f64 / decode_time.as_secs_f64(); + let switch_total: Duration = switches.iter().sum(); + let sustained = decoded as f64 / (decode_time + switch_total).as_secs_f64(); + println!( + "persona_switch: minds={minds} prompt={prompt_tokens} decode/turn={decode_tokens} rounds={rounds} turns={} | switch p50 {:.2} ms p90 {:.2} ms max {:.2} ms | decode {decode_tps:.1} tok/s | sustained incl. switches {sustained:.1} tok/s | prefill {:.1} s total | wall {:.1} s", + minds * rounds, + p(0.5), + p(0.9), + p(1.0), + prefill_time.as_secs_f64(), + run.elapsed().as_secs_f64() + ); + Ok(()) +} diff --git a/core/continuum-persona-llama/src/lib.rs b/core/continuum-persona-llama/src/lib.rs new file mode 100644 index 0000000000..e1fa058042 --- /dev/null +++ b/core/continuum-persona-llama/src/lib.rs @@ -0,0 +1,9 @@ +//! The persona engine's [`Tier`](continuum_persona_engine::residency::Tier) over the fork's native +//! persona blocks: one libllama context, two execution streams, and every other mind's blocks held in +//! RAM as she left them. The pipeline ([`continuum_persona_engine::pipeline::Roles`]) decides when a +//! mind moves; this adapter only performs the move (a native save out, a native bind in) and reports +//! it landed. + +mod unified_tier; + +pub use unified_tier::{Landed, Stream, UnifiedTier}; diff --git a/core/continuum-persona-llama/src/unified_tier.rs b/core/continuum-persona-llama/src/unified_tier.rs new file mode 100644 index 0000000000..837d357fdf --- /dev/null +++ b/core/continuum-persona-llama/src/unified_tier.rs @@ -0,0 +1,155 @@ +//! [`UnifiedTier`]: the persona engine's residency tier on one libllama context, as on the M5's unified +//! memory. Two execution streams: the active mind decodes in one while the next mind binds into the +//! other; every other mind's blocks stay in host memory exactly as she left them. A move out is the +//! fork's native save (her stream empties); a move in is its native bind (her blocks take an empty +//! stream, answering to the sequence she is bound as). Both are synchronous copies, so the fence a +//! move returns has already landed. + +use std::collections::HashMap; + +use continuum_persona_engine::persona::{Epoch, PersonaId}; +use continuum_persona_engine::residency::{Direction, Fence, FenceTag, Tier, TierRefusal}; +use llama::{Context, PersonaBlocks, PersonaOwner}; + +/// One of the context's two execution streams, by the sequence id the context knows it as. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Stream(i32); + +impl Stream { + /// The sequence id to decode her tokens as. + pub fn seq(self) -> i32 { + self.0 + } +} + +/// The two streams: one decodes, the other takes the next mind's copy-in. +const STREAMS: [Stream; 2] = [Stream(0), Stream(1)]; + +/// A move this tier performed: the fork's copies are synchronous, so it has landed when it exists. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Landed(FenceTag); + +impl Fence for Landed { + fn tag(&self) -> FenceTag { + self.0 + } + + fn complete(&self) -> bool { + true + } +} + +/// One mind this tier holds: her blocks (in RAM, or bound), the epoch they belong to, and the stream +/// she is bound to while she is in the execution stream. +struct Mind { + blocks: PersonaBlocks, + epoch: Epoch, + bound: Option, +} + +/// The persona engine's tier over one context's native persona blocks. +pub struct UnifiedTier<'c, 'm> { + ctx: &'c mut Context<'m>, + minds: HashMap, + /// Each persona's owner stamp for the fork, issued once per persona by this tier: exact within the + /// process the RAM tier lives in (a persona is a 128-bit id; the fork stamps 64 bits). + handles: HashMap, +} + +impl<'c, 'm> UnifiedTier<'c, 'm> { + pub fn new(ctx: &'c mut Context<'m>) -> Self { + Self { ctx, minds: HashMap::new(), handles: HashMap::new() } + } + + /// The stream `persona` is bound to, if she is in the execution stream. + pub fn stream_of(&self, persona: PersonaId) -> Option { + self.minds.get(&persona).and_then(|mind| mind.bound) + } + + /// The context, for the active mind's decode. + pub fn context(&mut self) -> &mut Context<'m> { + self.ctx + } + + /// How many minds this tier holds (bound or in RAM). + pub fn held(&self) -> usize { + self.minds.len() + } + + fn free_stream(&self) -> Option { + STREAMS.into_iter().find(|stream| !self.minds.values().any(|mind| mind.bound == Some(*stream))) + } +} + +impl Tier for UnifiedTier<'_, '_> { + type Fence = Landed; + + fn name(&self) -> &'static str { + TIER + } + + fn begin(&mut self, what: FenceTag) -> Result { + let persona = what.persona; + match what.direction { + Direction::In => { + let stream = self.free_stream().ok_or_else(|| refused(persona, "both streams are bound"))?; + let Self { ctx, minds, handles } = self; + let mind = mind_at(ctx, minds, handles, persona, what.epoch)?; + if mind.bound.is_some() { + return Err(refused(persona, "already bound")); + } + // a mind never saved has nothing to bind: she starts on an empty stream + if mind.blocks.owner().is_some() { + mind.blocks.bind(ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her bind"))?; + } + mind.bound = Some(stream); + } + Direction::Out => { + let Self { ctx, minds, .. } = self; + let mind = minds.get_mut(&persona).ok_or_else(|| refused(persona, "not held here"))?; + if mind.epoch != what.epoch { + return Err(refused(persona, "another epoch of her is bound")); + } + let stream = mind.bound.ok_or_else(|| refused(persona, "not bound"))?; + mind.blocks.save(ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her save"))?; + mind.bound = None; + } + } + Ok(Landed(what)) + } +} + +const TIER: &str = "unified"; + +fn refused(persona: PersonaId, reason: &'static str) -> TierRefusal { + TierRefusal { tier: TIER, persona, reason } +} + +/// Her mind at `epoch`: made with her owner on first sight; a new epoch starts her blocks over (refused while +/// the old ones are bound). +fn mind_at<'a>( + ctx: &mut Context<'_>, + minds: &'a mut HashMap, + handles: &mut HashMap, + persona: PersonaId, + epoch: Epoch, +) -> Result<&'a mut Mind, TierRefusal> { + if let Some(held) = minds.get(&persona) { + if held.epoch != epoch { + if held.bound.is_some() { + return Err(refused(persona, "a new epoch while her old blocks are bound")); + } + minds.remove(&persona); + } + } + let next = handles.len() as u64 + 1; + let handle = *handles.entry(persona).or_insert(next); + match minds.entry(persona) { + std::collections::hash_map::Entry::Occupied(held) => Ok(held.into_mut()), + std::collections::hash_map::Entry::Vacant(slot) => { + let owner = PersonaOwner { persona: handle, epoch: epoch.0 }; + let blocks = PersonaBlocks::new(ctx, owner).ok_or_else(|| refused(persona, "this context's memory has no persona move"))?; + Ok(slot.insert(Mind { blocks, epoch, bound: None })) + } + } +} diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index c9106fca66..318b9d7db0 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -37baf8c120e3455ec9ea9d81015b7c8bb60391d4 +a88f255cc7992589ff419f59b1ebc17e51ce4f1e diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 37baf8c120..a88f255cc7 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 37baf8c120e3455ec9ea9d81015b7c8bb60391d4 +Subproject commit a88f255cc7992589ff419f59b1ebc17e51ce4f1e From 370294fcc35adce3a0ad5e5031c0147d7712c63a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 01:57:29 -0600 Subject: [PATCH 08/12] UnifiedTier keeps a mind's custody on stale or failed epochs; streams own their occupancy; switches report the rebind kind (Codex on #6134) - A request for an older epoch than the one held is refused and leaves her blocks; a newer epoch prepares its blocks first and replaces the old ones only once they exist, so a refused allocation keeps custody. - Occupancy is the two streams' own [Option; 2], not a scan of every mind. - Each bind reports Rebind::SameSequence or Rebind::OtherSequence (the fork relabels her cells over her span on the latter); the example splits switch timings by kind and probes a stale epoch at the end. ## Measured (M5, Qwen3.6-35B-A3B Q4_K_M, serving down 07:47-07:57Z) - 4 / 8 / 16 minds, 4,096-token history: switch p50 8.57 / 8.57 / 8.41 ms; decode 58.0 / 57.8 / 57.5 tok/s; stale epoch refused and her blocks still bind, every run. - Rebind kind at equal history: 4,096 tokens same 9.15 ms (n=8) vs other 9.07 ms (n=10, 5 minds); 16,384 tokens same 27.80 ms (n=8, 4 minds) vs other 27.88 ms (n=10, 5 minds). The relabel walk is not measurable; the switch scales with the bytes copied. - Stage, handoff and copy-out run serially before her decode here, not overlapped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../examples/persona_switch.rs | 26 +++- core/continuum-persona-llama/src/lib.rs | 2 +- .../src/unified_tier.rs | 138 ++++++++++-------- 3 files changed, 101 insertions(+), 65 deletions(-) diff --git a/core/continuum-persona-llama/examples/persona_switch.rs b/core/continuum-persona-llama/examples/persona_switch.rs index 364194f02d..bca1f2e068 100644 --- a/core/continuum-persona-llama/examples/persona_switch.rs +++ b/core/continuum-persona-llama/examples/persona_switch.rs @@ -10,7 +10,7 @@ use std::time::{Duration, Instant}; use continuum_persona_engine::persona::{Epoch, PersonaId}; use continuum_persona_engine::pipeline::{Identified, Roles}; use continuum_persona_engine::residency::{Direction, FenceTag, Tier}; -use continuum_persona_llama::{Landed, UnifiedTier}; +use continuum_persona_llama::{Landed, Rebind, UnifiedTier}; use llama::{Batch, ContextParams, FlashAttn, Model, ModelParams}; /// One mind in the run: who she is, where her history ends, and her last sampled token. @@ -69,6 +69,7 @@ fn main() -> Result<(), String> { .collect::>()?; let mut roles: Roles = Roles::default(); + let (mut same_seq, mut other_seq) = (Vec::new(), Vec::new()); let (mut switches, mut decode_time, mut decoded, mut prefill_time) = (Vec::new(), Duration::ZERO, 0usize, Duration::ZERO); let run = Instant::now(); for turn in 0..minds * rounds { @@ -76,6 +77,7 @@ fn main() -> Result<(), String> { let next = parked.remove(0); let t = Instant::now(); let fence = tier.begin(FenceTag { persona: next.id, epoch: next.epoch, direction: Direction::In }).map_err(|e| e.to_string())?; + let rebind = tier.last_rebind(); roles.stage(next, fence).map_err(|r| format!("{:?}", r.reason))?; roles.handoff().map_err(|e| format!("{e:?}"))?; if let Some(out) = roles.awaiting_copy_out() { @@ -86,6 +88,11 @@ fn main() -> Result<(), String> { let switched = t.elapsed(); if turn > 0 { switches.push(switched); + match rebind { + Some(Rebind::SameSequence) => same_seq.push(switched), + Some(Rebind::OtherSequence) => other_seq.push(switched), + None => {} + } } let mind = roles.active_mut().ok_or("no active mind after handoff")?; @@ -118,9 +125,17 @@ fn main() -> Result<(), String> { decoded += decode_tokens; } + // a stale request for an older epoch of a held mind is refused and leaves her blocks: she still binds + let probe = parked.first().ok_or("no parked mind to probe")?; + let stale = tier.begin(FenceTag { persona: probe.id, epoch: Epoch(0), direction: Direction::In }); + let kept = tier.begin(FenceTag { persona: probe.id, epoch: probe.epoch, direction: Direction::In }).is_ok(); + println!("persona_switch: stale epoch refused={} her blocks still bind={kept}", stale.is_err()); switches.sort(); + same_seq.sort(); + other_seq.sort(); let ms = |d: Duration| d.as_secs_f64() * 1e3; - let p = |q: f64| switches.get(((switches.len() as f64 - 1.0) * q) as usize).copied().map(ms).unwrap_or(0.0); + let at = |v: &[Duration], q: f64| v.get(((v.len().max(1) as f64 - 1.0) * q) as usize).copied().map(ms).unwrap_or(0.0); // unwrap_or: an empty class prints 0 + let p = |q: f64| at(&switches, q); let decode_tps = decoded as f64 / decode_time.as_secs_f64(); let switch_total: Duration = switches.iter().sum(); let sustained = decoded as f64 / (decode_time + switch_total).as_secs_f64(); @@ -133,5 +148,12 @@ fn main() -> Result<(), String> { prefill_time.as_secs_f64(), run.elapsed().as_secs_f64() ); + println!( + "persona_switch: rebinds (binds of a mind saved before) same sequence n={} p50 {:.2} ms | other sequence (cells relabeled over her span) n={} p50 {:.2} ms; stage, handoff and copy-out run serially before her decode, not overlapped", + same_seq.len(), + at(&same_seq, 0.5), + other_seq.len(), + at(&other_seq, 0.5) + ); Ok(()) } diff --git a/core/continuum-persona-llama/src/lib.rs b/core/continuum-persona-llama/src/lib.rs index e1fa058042..e32c587f05 100644 --- a/core/continuum-persona-llama/src/lib.rs +++ b/core/continuum-persona-llama/src/lib.rs @@ -6,4 +6,4 @@ mod unified_tier; -pub use unified_tier::{Landed, Stream, UnifiedTier}; +pub use unified_tier::{Landed, Rebind, Stream, UnifiedTier}; diff --git a/core/continuum-persona-llama/src/unified_tier.rs b/core/continuum-persona-llama/src/unified_tier.rs index 837d357fdf..f7253fdf92 100644 --- a/core/continuum-persona-llama/src/unified_tier.rs +++ b/core/continuum-persona-llama/src/unified_tier.rs @@ -22,9 +22,6 @@ impl Stream { } } -/// The two streams: one decodes, the other takes the next mind's copy-in. -const STREAMS: [Stream; 2] = [Stream(0), Stream(1)]; - /// A move this tier performed: the fork's copies are synchronous, so it has landed when it exists. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Landed(FenceTag); @@ -39,31 +36,42 @@ impl Fence for Landed { } } +/// How a mind's last bind met her blocks: on the sequence she was saved from (her cells keep their +/// label), or on the other one (the fork relabels her cells, a walk over her span; Codex on #6134). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Rebind { + SameSequence, + OtherSequence, +} + /// One mind this tier holds: her blocks (in RAM, or bound), the epoch they belong to, and the stream -/// she is bound to while she is in the execution stream. +/// she was last saved from. struct Mind { blocks: PersonaBlocks, epoch: Epoch, - bound: Option, + saved_from: Option, } /// The persona engine's tier over one context's native persona blocks. pub struct UnifiedTier<'c, 'm> { ctx: &'c mut Context<'m>, + /// Who occupies each execution stream: occupancy is the streams', never a scan of every mind. + streams: [Option; 2], minds: HashMap, /// Each persona's owner stamp for the fork, issued once per persona by this tier: exact within the /// process the RAM tier lives in (a persona is a 128-bit id; the fork stamps 64 bits). handles: HashMap, + last_rebind: Option, } impl<'c, 'm> UnifiedTier<'c, 'm> { pub fn new(ctx: &'c mut Context<'m>) -> Self { - Self { ctx, minds: HashMap::new(), handles: HashMap::new() } + Self { ctx, streams: [None, None], minds: HashMap::new(), handles: HashMap::new(), last_rebind: None } } /// The stream `persona` is bound to, if she is in the execution stream. pub fn stream_of(&self, persona: PersonaId) -> Option { - self.minds.get(&persona).and_then(|mind| mind.bound) + self.streams.iter().position(|held| *held == Some(persona)).map(stream_at) } /// The context, for the active mind's decode. @@ -76,8 +84,61 @@ impl<'c, 'm> UnifiedTier<'c, 'm> { self.minds.len() } - fn free_stream(&self) -> Option { - STREAMS.into_iter().find(|stream| !self.minds.values().any(|mind| mind.bound == Some(*stream))) + /// How the last move in met her blocks; `None` when she had never been saved. + pub fn last_rebind(&self) -> Option { + self.last_rebind + } + + fn move_in(&mut self, persona: PersonaId, epoch: Epoch) -> Result<(), TierRefusal> { + if self.stream_of(persona).is_some() { + return Err(refused(persona, "already bound")); + } + let slot = self.streams.iter().position(Option::is_none).ok_or_else(|| refused(persona, "both streams are bound"))?; + let stream = stream_at(slot); + self.hold(persona, epoch)?; + let mind = self.minds.get_mut(&persona).ok_or_else(|| refused(persona, "not held here"))?; + // a mind never saved has nothing to bind: she starts on an empty stream + self.last_rebind = None; + if let Some(from) = mind.saved_from { + mind.blocks.bind(self.ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her bind"))?; + self.last_rebind = Some(if from == stream { Rebind::SameSequence } else { Rebind::OtherSequence }); + } + self.streams[slot] = Some(persona); + Ok(()) + } + + fn move_out(&mut self, persona: PersonaId, epoch: Epoch) -> Result<(), TierRefusal> { + let slot = self.streams.iter().position(|held| *held == Some(persona)).ok_or_else(|| refused(persona, "not bound"))?; + let stream = stream_at(slot); + let mind = self.minds.get_mut(&persona).ok_or_else(|| refused(persona, "not held here"))?; + if mind.epoch != epoch { + return Err(refused(persona, "another epoch of her is bound")); + } + mind.blocks.save(self.ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her save"))?; + mind.saved_from = Some(stream); + self.streams[slot] = None; + Ok(()) + } + + /// Her blocks at `epoch`, made with her owner on first sight. An older epoch than the one held is + /// stale and refused, leaving her blocks as they are. A newer epoch prepares its blocks first and + /// replaces the old ones only once they exist, so a refused allocation keeps her custody (Codex on + /// #6134). + fn hold(&mut self, persona: PersonaId, epoch: Epoch) -> Result<(), TierRefusal> { + if let Some(held) = self.minds.get(&persona) { + if epoch == held.epoch { + return Ok(()); + } + if epoch < held.epoch { + return Err(refused(persona, "a stale epoch: her newer blocks are kept")); + } + } + let next = self.handles.len() as u64 + 1; + let handle = *self.handles.entry(persona).or_insert(next); + let owner = PersonaOwner { persona: handle, epoch: epoch.0 }; + let blocks = PersonaBlocks::new(self.ctx, owner).ok_or_else(|| refused(persona, "this context's memory has no persona move"))?; + self.minds.insert(persona, Mind { blocks, epoch, saved_from: None }); + Ok(()) } } @@ -89,31 +150,9 @@ impl Tier for UnifiedTier<'_, '_> { } fn begin(&mut self, what: FenceTag) -> Result { - let persona = what.persona; match what.direction { - Direction::In => { - let stream = self.free_stream().ok_or_else(|| refused(persona, "both streams are bound"))?; - let Self { ctx, minds, handles } = self; - let mind = mind_at(ctx, minds, handles, persona, what.epoch)?; - if mind.bound.is_some() { - return Err(refused(persona, "already bound")); - } - // a mind never saved has nothing to bind: she starts on an empty stream - if mind.blocks.owner().is_some() { - mind.blocks.bind(ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her bind"))?; - } - mind.bound = Some(stream); - } - Direction::Out => { - let Self { ctx, minds, .. } = self; - let mind = minds.get_mut(&persona).ok_or_else(|| refused(persona, "not held here"))?; - if mind.epoch != what.epoch { - return Err(refused(persona, "another epoch of her is bound")); - } - let stream = mind.bound.ok_or_else(|| refused(persona, "not bound"))?; - mind.blocks.save(ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her save"))?; - mind.bound = None; - } + Direction::In => self.move_in(what.persona, what.epoch)?, + Direction::Out => self.move_out(what.persona, what.epoch)?, } Ok(Landed(what)) } @@ -121,35 +160,10 @@ impl Tier for UnifiedTier<'_, '_> { const TIER: &str = "unified"; -fn refused(persona: PersonaId, reason: &'static str) -> TierRefusal { - TierRefusal { tier: TIER, persona, reason } +fn stream_at(slot: usize) -> Stream { + Stream(slot as i32) } -/// Her mind at `epoch`: made with her owner on first sight; a new epoch starts her blocks over (refused while -/// the old ones are bound). -fn mind_at<'a>( - ctx: &mut Context<'_>, - minds: &'a mut HashMap, - handles: &mut HashMap, - persona: PersonaId, - epoch: Epoch, -) -> Result<&'a mut Mind, TierRefusal> { - if let Some(held) = minds.get(&persona) { - if held.epoch != epoch { - if held.bound.is_some() { - return Err(refused(persona, "a new epoch while her old blocks are bound")); - } - minds.remove(&persona); - } - } - let next = handles.len() as u64 + 1; - let handle = *handles.entry(persona).or_insert(next); - match minds.entry(persona) { - std::collections::hash_map::Entry::Occupied(held) => Ok(held.into_mut()), - std::collections::hash_map::Entry::Vacant(slot) => { - let owner = PersonaOwner { persona: handle, epoch: epoch.0 }; - let blocks = PersonaBlocks::new(ctx, owner).ok_or_else(|| refused(persona, "this context's memory has no persona move"))?; - Ok(slot.insert(Mind { blocks, epoch, bound: None })) - } - } +fn refused(persona: PersonaId, reason: &'static str) -> TierRefusal { + TierRefusal { tier: TIER, persona, reason } } From d815ce50283a4991333c6534a377b9de509a1a5a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 02:05:05 -0600 Subject: [PATCH 09/12] Test CI dependency selection for the persona llama adapter --- tools/scripts/tests/ci-change-scope.test.cjs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index 12d0cd6a73..c718d1e2d8 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', 'continuum-persona-engine']; +const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-saved-state', 'continuum-context', 'continuum-flow', 'continuum-proving-types', 'continuum-persona-engine', 'continuum-persona-llama']; 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,15 +148,15 @@ 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')); + assert.deepEqual(scope(['core/continuum-persona-engine/src/persona/unit.rs']), crates('continuum-persona-engine', 'continuum-persona-llama')); 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', 'continuum-persona-engine'].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', 'continuum-persona-llama'].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 -> ... - assert.deepEqual(scope(['core/llama/src/lib.rs']), belowMind); + assert.deepEqual(scope(['core/llama/src/lib.rs']), crates(...belowMind.crates, 'continuum-persona-llama')); assert.deepEqual(scope(['core/continuum-mind/src/a.rs', 'core/continuum-live/src/b.rs']), crates('continuum-live', 'continuum-perception', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); // A crate's own manifest is that crate's change; a rename counts both ends. assert.deepEqual(scope(['core/continuum-hands/Cargo.toml']), crates('continuum-hands', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); From de0e34a9776cbbca35a92436c428543fecbc09ca Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 10:14:54 -0600 Subject: [PATCH 10/12] UnifiedTier binds a new mind only on a stream the engine reports empty, and keeps the fork's refusals Codex on #6134 (d815ce502): UnifiedTier::new takes any live Context with streams = [None, None], and a never-saved mind's move in marked stream 0 occupied without asking whether its sequence held state. A tier wrapping a context already in use could therefore report a successful first bind over prior KV. And move_in/move_out mapped the fork's typed refusals to a fixed string. - move_in, for a mind never saved, asks the engine's own memory (memory_seq_pos_max on the stream's sequence) and refuses "her stream already holds another sequence's state" unless it is -1 (empty). The evidence is the engine's, never this tier's bookkeeping; the refusal changes nothing. - TierRefusal carries Native: NotAsked (the tier's own precondition) or Refused { status, name } (the fork's llama_persona status and its name). move_in/move_out keep the fork's refusal instead of erasing it; the error text appends it. - persona_switch runs the adoption scenario before its measurement: one token decoded into sequence 0 before the tier exists; a new mind's move in is refused and sequence 0's state is unchanged; after the stream is cleared she binds. (Needs a real model, as the harness does; it is not a CI test.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../continuum-persona-engine/src/residency.rs | 2 +- .../src/residency/tier.rs | 24 +++++++++++++-- .../examples/persona_switch.rs | 28 ++++++++++++++++++ .../src/unified_tier.rs | 29 ++++++++++++++----- 4 files changed, 72 insertions(+), 11 deletions(-) diff --git a/core/continuum-persona-engine/src/residency.rs b/core/continuum-persona-engine/src/residency.rs index 69aaf368a1..43866e4024 100644 --- a/core/continuum-persona-engine/src/residency.rs +++ b/core/continuum-persona-engine/src/residency.rs @@ -4,4 +4,4 @@ mod fence; mod tier; pub use fence::{Direction, Fence, FenceTag}; -pub use tier::{Tier, TierRefusal}; +pub use tier::{Native, Tier, TierRefusal}; diff --git a/core/continuum-persona-engine/src/residency/tier.rs b/core/continuum-persona-engine/src/residency/tier.rs index 2b58330489..7826e8e414 100644 --- a/core/continuum-persona-engine/src/residency/tier.rs +++ b/core/continuum-persona-engine/src/residency/tier.rs @@ -1,4 +1,4 @@ -//! [`Tier`]: one contract for every residency tier (device VRAM, pinned host RAM, the unified +//! [`Tier`]: o#[error("{tier}: {reason} for persona {persona:?}{native}")]e 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. @@ -7,11 +7,31 @@ 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:?}")] +#[error("{tier}: {reason} for persona {persona:?}{native}")] pub struct TierRefusal { pub tier: &'static str, pub persona: PersonaId, pub reason: &'static str, + /// The backend's own refusal, kept rather than erased. + pub native: Native, +} + +/// What the backend itself said when the tier refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Native { + /// The refusal is the tier's own (a precondition it checked); the backend was not asked. + NotAsked, + /// The backend refused, by its status and the name it gives that status. + Refused { status: i32, name: String }, +} + +impl std::fmt::Display for Native { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NotAsked => Ok(()), + Self::Refused { status, name } => write!(f, " (backend status {status}: {name})"), + } + } } /// A residency tier. diff --git a/core/continuum-persona-llama/examples/persona_switch.rs b/core/continuum-persona-llama/examples/persona_switch.rs index bca1f2e068..47837d5651 100644 --- a/core/continuum-persona-llama/examples/persona_switch.rs +++ b/core/continuum-persona-llama/examples/persona_switch.rs @@ -45,6 +45,33 @@ fn arg(args: &[String], i: usize, what: &str) -> Result { args.get(i).ok_or(format!("missing {what}"))?.parse().map_err(|e| format!("{what}: {e}")) } +/// Codex on #6134: a tier wrapping a context already in use must not report a first bind over the +/// state another sequence holds there. One token is decoded into sequence 0 before the tier exists; a +/// new mind's move in must be refused with that state untouched, and succeed once the stream is empty. +fn adopted_context_is_refused(model: &Model, ctx: &mut llama::Context<'_>) -> Result<(), String> { + let token = *model.tokenize("held", true, false)?.first().ok_or("no token for the probe")?; + let mut batch = Batch::allocated(1, 1); + batch.push(token, 0, &[0], false); + ctx.decode(&batch)?; + let mind = FenceTag { persona: PersonaId(uuid::Uuid::new_v4()), epoch: Epoch(1), direction: Direction::In }; + { + let mut tier = UnifiedTier::new(ctx); + if tier.begin(mind).is_ok() { + return Err("adoption: a new mind was bound over sequence 0's state".into()); + } + } + if ctx.memory_seq_pos_max(0) != 0 { + return Err("adoption: the refused move changed sequence 0's state".into()); + } + ctx.memory_seq_rm(0, -1, -1); + if UnifiedTier::new(ctx).begin(mind).is_err() { + return Err("adoption: a new mind was refused an empty stream".into()); + } + ctx.memory_seq_rm(0, -1, -1); + println!("persona_switch: adoption: a new mind is refused over held state and bound on an empty stream"); + Ok(()) +} + fn main() -> Result<(), String> { let args: Vec = std::env::args().collect(); let model_path = args.get(1).ok_or("usage: persona_switch ")?; @@ -57,6 +84,7 @@ fn main() -> Result<(), String> { let window = (prompt_tokens + decode_tokens * rounds + 64) as u32; let params = ContextParams { n_ctx: window * 2, n_batch: 2048, n_ubatch: 2048, n_seq_max: 2, flash_attn: FlashAttn::Enabled, ..ContextParams::default() }; let mut ctx = model.new_context(params)?; + adopted_context_is_refused(&model, &mut ctx)?; let mut tier = UnifiedTier::new(&mut ctx); let mut parked: Vec = (0..minds) diff --git a/core/continuum-persona-llama/src/unified_tier.rs b/core/continuum-persona-llama/src/unified_tier.rs index f7253fdf92..dfb0149de8 100644 --- a/core/continuum-persona-llama/src/unified_tier.rs +++ b/core/continuum-persona-llama/src/unified_tier.rs @@ -8,8 +8,8 @@ use std::collections::HashMap; use continuum_persona_engine::persona::{Epoch, PersonaId}; -use continuum_persona_engine::residency::{Direction, Fence, FenceTag, Tier, TierRefusal}; -use llama::{Context, PersonaBlocks, PersonaOwner}; +use continuum_persona_engine::residency::{Direction, Fence, FenceTag, Native, Tier, TierRefusal}; +use llama::{Context, PersonaBlocks, PersonaOwner, PersonaRefusal}; /// One of the context's two execution streams, by the sequence id the context knows it as. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -97,11 +97,19 @@ impl<'c, 'm> UnifiedTier<'c, 'm> { let stream = stream_at(slot); self.hold(persona, epoch)?; let mind = self.minds.get_mut(&persona).ok_or_else(|| refused(persona, "not held here"))?; - // a mind never saved has nothing to bind: she starts on an empty stream self.last_rebind = None; - if let Some(from) = mind.saved_from { - mind.blocks.bind(self.ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her bind"))?; - self.last_rebind = Some(if from == stream { Rebind::SameSequence } else { Rebind::OtherSequence }); + match mind.saved_from { + // A mind never saved has nothing to bind: she starts on this stream as it is, so it must + // hold nothing (the context may have been in use before this tier wrapped it; Codex on + // #6134). The engine's own memory is the evidence, never this tier's bookkeeping. + None if self.ctx.memory_seq_pos_max(stream.seq()) >= 0 => { + return Err(refused(persona, "her stream already holds another sequence's state")); + } + None => {} + Some(from) => { + mind.blocks.bind(self.ctx, stream.seq()).map_err(|e| native(persona, "the fork refused her bind", e))?; + self.last_rebind = Some(if from == stream { Rebind::SameSequence } else { Rebind::OtherSequence }); + } } self.streams[slot] = Some(persona); Ok(()) @@ -114,7 +122,7 @@ impl<'c, 'm> UnifiedTier<'c, 'm> { if mind.epoch != epoch { return Err(refused(persona, "another epoch of her is bound")); } - mind.blocks.save(self.ctx, stream.seq()).map_err(|_| refused(persona, "the fork refused her save"))?; + mind.blocks.save(self.ctx, stream.seq()).map_err(|e| native(persona, "the fork refused her save", e))?; mind.saved_from = Some(stream); self.streams[slot] = None; Ok(()) @@ -165,5 +173,10 @@ fn stream_at(slot: usize) -> Stream { } fn refused(persona: PersonaId, reason: &'static str) -> TierRefusal { - TierRefusal { tier: TIER, persona, reason } + TierRefusal { tier: TIER, persona, reason, native: Native::NotAsked } +} + +/// The fork refused: keep its status and name in the refusal. +fn native(persona: PersonaId, reason: &'static str, refusal: PersonaRefusal) -> TierRefusal { + TierRefusal { tier: TIER, persona, reason, native: Native::Refused { status: refusal.status, name: refusal.name } } } From 1865973eee095c58f4607a50519576ee52d321fe Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 10:23:24 -0600 Subject: [PATCH 11/12] PersonaBlocks::bind takes the owner the transfer is for, and refuses another persona's or a stale epoch's blocks before the fork Codex on #6132 (ea955a81a): bind(ctx, seq) carried no expected persona or epoch. The fork's bind/load validate a handle's blocks against that handle's own identity, which keeps blocks consistent but cannot detect that the caller selected the wrong intact handle. - bind(ctx, seq, expected: PersonaOwner) compares the handle's stamp (the owner its last completed save wrote) with the transfer's owner, persona AND epoch, and refuses BindRefusal::WrongOwner { expected, held } before calling the fork. The destination is untouched. A never-saved handle has no stamp and is refused the same way. - The fork's own refusal stays typed as BindRefusal::Native(PersonaRefusal). - Test only_the_expected_owner_and_epoch_bind: two intact handles at one reusable sequence (another persona, the same persona at a stale epoch, an unstamped handle) are each refused; the expected owner binds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/llama/src/safe.rs | 2 +- core/llama/src/safe/persona.rs | 48 +++++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/core/llama/src/safe.rs b/core/llama/src/safe.rs index c1ca4e8cfb..3c14a6a4da 100644 --- a/core/llama/src/safe.rs +++ b/core/llama/src/safe.rs @@ -14,7 +14,7 @@ pub use backend_init::*; mod expert_eval_cb; pub use expert_eval_cb::*; mod persona; -pub use persona::{PersonaBlocks, PersonaOwner, PersonaRefusal}; +pub use persona::{BindRefusal, PersonaBlocks, PersonaOwner, PersonaRefusal}; // ─── Tests ─────────────────────────────────────────────────────────────── #[cfg(test)] diff --git a/core/llama/src/safe/persona.rs b/core/llama/src/safe/persona.rs index 46a81d5a27..f5e9f82419 100644 --- a/core/llama/src/safe/persona.rs +++ b/core/llama/src/safe/persona.rs @@ -24,6 +24,24 @@ pub struct PersonaRefusal { pub name: String, } +/// Why a bind was refused: the blocks are not the expected owner's, or the fork refused. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum BindRefusal { + #[error("these blocks are stamped {held:?}, not the expected {expected:?}")] + WrongOwner { expected: PersonaOwner, held: Option }, + #[error(transparent)] + Native(#[from] PersonaRefusal), +} + +/// The handle's stamp against the transfer's owner: equal persona AND epoch, or refused. A handle +/// never saved (no stamp) has nothing to bind. +fn owner_matches(held: Option, expected: PersonaOwner) -> Result<(), BindRefusal> { + match held { + Some(held) if held == expected => Ok(()), + held => Err(BindRefusal::WrongOwner { expected, held }), + } +} + fn status(code: i32) -> Result<(), PersonaRefusal> { if code == 0 { return Ok(()); @@ -72,10 +90,15 @@ impl PersonaBlocks { } /// Bind these blocks into `ctx` as sequence `seq`, in an empty stream the memory chooses (the - /// caller never numbers streams); `no_empty_stream` when none is empty. - pub fn bind(&mut self, ctx: &mut Context<'_>, seq: i32) -> Result<(), PersonaRefusal> { + /// caller never numbers streams); `no_empty_stream` when none is empty. The caller names the + /// owner the transfer is FOR: blocks stamped for another persona, or for another epoch of her (a + /// stale generation), are refused before the fork is asked, so a wrong but intact handle never + /// binds and the destination is untouched (Codex on #6132; the fork checks only that a handle's + /// blocks match the handle itself). + pub fn bind(&mut self, ctx: &mut Context<'_>, seq: i32, expected: PersonaOwner) -> Result<(), BindRefusal> { + owner_matches(self.owner(), expected)?; // SAFETY: both pointers are live; the fork validates before writing and refuses whole. - status(unsafe { sys::llama_persona_bind(ctx.as_ptr(), seq, self.ptr.as_ptr()) }) + status(unsafe { sys::llama_persona_bind(ctx.as_ptr(), seq, self.ptr.as_ptr()) }).map_err(BindRefusal::Native) } /// The owner stamped by the last completed save; `None` before one. @@ -105,3 +128,22 @@ impl Drop for PersonaBlocks { unsafe { sys::llama_persona_free(self.ptr.as_ptr()) } } } + +#[cfg(test)] +mod tests { + use super::*; + + const HER: PersonaOwner = PersonaOwner { persona: 7, epoch: 3 }; + + // what this catches (Codex on #6132): two intact handles at one reusable sequence. The bind of + // the wrong one, or of a stale epoch of the right one, is refused before the fork is asked. + #[test] + fn only_the_expected_owner_and_epoch_bind() { + assert_eq!(owner_matches(Some(HER), HER), Ok(())); + let other = PersonaOwner { persona: 8, epoch: 3 }; + assert_eq!(owner_matches(Some(other), HER), Err(BindRefusal::WrongOwner { expected: HER, held: Some(other) })); + let stale = PersonaOwner { persona: 7, epoch: 2 }; + assert_eq!(owner_matches(Some(stale), HER), Err(BindRefusal::WrongOwner { expected: HER, held: Some(stale) })); + assert_eq!(owner_matches(None, HER), Err(BindRefusal::WrongOwner { expected: HER, held: None })); + } +} From 16826fc296528f92e830843dab5569328b3d8de2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 10:24:49 -0600 Subject: [PATCH 12/12] UnifiedTier checks every move before it replaces her blocks; binds name her owner and epoch Codex on #6134 (de0e34a97): move_in called hold before checking occupancy. With epoch 1 parked in RAM and the chosen stream occupied (an adopted context), hold(epoch 2) replaced and dropped epoch 1's blocks, and only then did move_in refuse. - move_in decides everything before it changes anything: a stale epoch is refused; the same epoch rebinds from the stream she was saved from; a new mind or a newer epoch starts over, and only then is the stream's emptiness checked against the engine's own memory. hold (which may replace an older epoch's blocks) runs only after every check passed, so a refusal keeps the blocks she had. - The bind passes the owner the transfer is for (her issued stamp at this epoch), through #6132's new PersonaBlocks::bind(ctx, seq, expected); a wrong or stale stamp is a refusal naming it, a fork refusal keeps its native status. - tier.rs: the first doc line had error-attribute text pasted into it; restored. - persona_switch replays the scenario before measuring: epoch 1 decodes and parks; another sequence's state lands on her stream; epoch 2 is refused there; the stream is cleared; epoch 1 binds back at the position she left. (Real model, so not CI. Byte-identical continuation after a bind is the fork's test-persona-blocks.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/residency/tier.rs | 2 +- .../examples/persona_switch.rs | 37 +++++++++++++++ .../src/unified_tier.rs | 46 +++++++++++++------ 3 files changed, 71 insertions(+), 14 deletions(-) diff --git a/core/continuum-persona-engine/src/residency/tier.rs b/core/continuum-persona-engine/src/residency/tier.rs index 7826e8e414..269d44ba08 100644 --- a/core/continuum-persona-engine/src/residency/tier.rs +++ b/core/continuum-persona-engine/src/residency/tier.rs @@ -1,4 +1,4 @@ -//! [`Tier`]: o#[error("{tier}: {reason} for persona {persona:?}{native}")]e contract for every residency tier (device VRAM, pinned host RAM, the unified +//! [`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. diff --git a/core/continuum-persona-llama/examples/persona_switch.rs b/core/continuum-persona-llama/examples/persona_switch.rs index 47837d5651..66c5438ec5 100644 --- a/core/continuum-persona-llama/examples/persona_switch.rs +++ b/core/continuum-persona-llama/examples/persona_switch.rs @@ -72,6 +72,42 @@ fn adopted_context_is_refused(model: &Model, ctx: &mut llama::Context<'_>) -> Re Ok(()) } +/// Codex on #6134 (de0e34a97): a refused move must not cost her the blocks she had. Epoch 1 decodes and +/// parks in RAM; another sequence's state lands on her stream; epoch 2's move in is refused there; once +/// the stream is clear epoch 1 binds back at the position she left (her byte-identical continuation +/// after a bind is the fork's own test, test-persona-blocks). +fn a_refused_newer_epoch_keeps_her_parked_blocks(model: &Model, ctx: &mut llama::Context<'_>) -> Result<(), String> { + let tokens = model.tokenize("She keeps her own notes.", true, false)?; + let her = PersonaId(uuid::Uuid::new_v4()); + let tag = |epoch, direction| FenceTag { persona: her, epoch: Epoch(epoch), direction }; + let mut tier = UnifiedTier::new(ctx); + tier.begin(tag(1, Direction::In)).map_err(|e| e.to_string())?; + let seq = tier.stream_of(her).ok_or("replay: she is not bound")?.seq(); + let mut batch = Batch::allocated(tokens.len() as i32, 1); + for (i, &t) in tokens.iter().enumerate() { + batch.push(t, i as i32, &[seq], false); + } + tier.context().decode(&batch)?; + let held_to = tier.context().memory_seq_pos_max(seq); + tier.begin(tag(1, Direction::Out)).map_err(|e| e.to_string())?; + let first = *tokens.first().ok_or("replay: no tokens")?; + let mut other = Batch::allocated(1, 1); + other.push(first, 0, &[seq], false); + tier.context().decode(&other)?; + if tier.begin(tag(2, Direction::In)).is_ok() { + return Err("replay: epoch 2 was bound over another sequence's state".into()); + } + tier.context().memory_seq_rm(seq, -1, -1); + tier.begin(tag(1, Direction::In)).map_err(|e| format!("replay: her parked epoch 1 was lost: {e}"))?; + let back = tier.stream_of(her).ok_or("replay: she is not bound again")?.seq(); + if tier.context().memory_seq_pos_max(back) != held_to { + return Err(format!("replay: epoch 1 came back holding {} instead of {held_to}", tier.context().memory_seq_pos_max(back))); + } + tier.begin(tag(1, Direction::Out)).map_err(|e| e.to_string())?; + println!("persona_switch: replay: a refused newer epoch kept her parked epoch 1, which bound back at position {held_to}"); + Ok(()) +} + fn main() -> Result<(), String> { let args: Vec = std::env::args().collect(); let model_path = args.get(1).ok_or("usage: persona_switch ")?; @@ -85,6 +121,7 @@ fn main() -> Result<(), String> { let params = ContextParams { n_ctx: window * 2, n_batch: 2048, n_ubatch: 2048, n_seq_max: 2, flash_attn: FlashAttn::Enabled, ..ContextParams::default() }; let mut ctx = model.new_context(params)?; adopted_context_is_refused(&model, &mut ctx)?; + a_refused_newer_epoch_keeps_her_parked_blocks(&model, &mut ctx)?; let mut tier = UnifiedTier::new(&mut ctx); let mut parked: Vec = (0..minds) diff --git a/core/continuum-persona-llama/src/unified_tier.rs b/core/continuum-persona-llama/src/unified_tier.rs index dfb0149de8..36ae474950 100644 --- a/core/continuum-persona-llama/src/unified_tier.rs +++ b/core/continuum-persona-llama/src/unified_tier.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use continuum_persona_engine::persona::{Epoch, PersonaId}; use continuum_persona_engine::residency::{Direction, Fence, FenceTag, Native, Tier, TierRefusal}; -use llama::{Context, PersonaBlocks, PersonaOwner, PersonaRefusal}; +use llama::{BindRefusal, Context, PersonaBlocks, PersonaOwner, PersonaRefusal}; /// One of the context's two execution streams, by the sequence id the context knows it as. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -95,26 +95,38 @@ impl<'c, 'm> UnifiedTier<'c, 'm> { } let slot = self.streams.iter().position(Option::is_none).ok_or_else(|| refused(persona, "both streams are bound"))?; let stream = stream_at(slot); + // Every check runs before anything changes (Codex on #6134): a newer epoch replaces her older + // blocks only once the move is known to succeed, so a refusal keeps the blocks she had. + let rebind_from = match self.minds.get(&persona) { + Some(held) if epoch < held.epoch => return Err(refused(persona, "a stale epoch: her newer blocks are kept")), + Some(held) if epoch == held.epoch => held.saved_from, + // a mind never seen, or a newer epoch of her, starts over on this stream + _ => None, + }; + // A mind with nothing to bind starts on this stream as it is, so it must hold nothing (the + // context may have been in use before this tier wrapped it). The engine's own memory is the + // evidence, never this tier's bookkeeping. + if rebind_from.is_none() && self.ctx.memory_seq_pos_max(stream.seq()) >= 0 { + return Err(refused(persona, "her stream already holds another sequence's state")); + } self.hold(persona, epoch)?; + let owner = self.owner_of(persona, epoch)?; let mind = self.minds.get_mut(&persona).ok_or_else(|| refused(persona, "not held here"))?; self.last_rebind = None; - match mind.saved_from { - // A mind never saved has nothing to bind: she starts on this stream as it is, so it must - // hold nothing (the context may have been in use before this tier wrapped it; Codex on - // #6134). The engine's own memory is the evidence, never this tier's bookkeeping. - None if self.ctx.memory_seq_pos_max(stream.seq()) >= 0 => { - return Err(refused(persona, "her stream already holds another sequence's state")); - } - None => {} - Some(from) => { - mind.blocks.bind(self.ctx, stream.seq()).map_err(|e| native(persona, "the fork refused her bind", e))?; - self.last_rebind = Some(if from == stream { Rebind::SameSequence } else { Rebind::OtherSequence }); - } + if let Some(from) = rebind_from { + mind.blocks.bind(self.ctx, stream.seq(), owner).map_err(|e| bind_refused(persona, e))?; + self.last_rebind = Some(if from == stream { Rebind::SameSequence } else { Rebind::OtherSequence }); } self.streams[slot] = Some(persona); Ok(()) } + /// The owner stamp issued to `persona`, at `epoch`: what her blocks must carry to bind. + fn owner_of(&self, persona: PersonaId, epoch: Epoch) -> Result { + let handle = *self.handles.get(&persona).ok_or_else(|| refused(persona, "no owner stamp issued to her"))?; + Ok(PersonaOwner { persona: handle, epoch: epoch.0 }) + } + fn move_out(&mut self, persona: PersonaId, epoch: Epoch) -> Result<(), TierRefusal> { let slot = self.streams.iter().position(|held| *held == Some(persona)).ok_or_else(|| refused(persona, "not bound"))?; let stream = stream_at(slot); @@ -180,3 +192,11 @@ fn refused(persona: PersonaId, reason: &'static str) -> TierRefusal { fn native(persona: PersonaId, reason: &'static str, refusal: PersonaRefusal) -> TierRefusal { TierRefusal { tier: TIER, persona, reason, native: Native::Refused { status: refusal.status, name: refusal.name } } } + +/// A refused bind, by who refused: her blocks' stamp (another owner or a stale epoch) or the fork. +fn bind_refused(persona: PersonaId, refusal: BindRefusal) -> TierRefusal { + match refusal { + BindRefusal::WrongOwner { .. } => refused(persona, "her blocks are stamped for another owner or epoch"), + BindRefusal::Native(native_refusal) => native(persona, "the fork refused her bind", native_refusal), + } +}