From cfcf0c22d479d9447eec8ec5993d183c28a872f9 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 13:43:41 -0600 Subject: [PATCH 1/2] The persona scheduler publishes the geometry its context applied, per incarnation (agreed with Codex) Scheduler::state() is a watch of EngineState: Starting(incarnation), Ready(EngineGeometry) read from the created context (llama.cpp's applied n_ctx / n_batch / n_ubatch, the KV types and attention it was made with, decoding = 1, staging = STREAMS - 1), or Refused with the reason. Each snapshot names the engine incarnation it came from (rising per spawn), so serving retires a stale observation. The batch the driver prefills in is now the applied one, not the request's. llama: Context::n_batch / n_ubatch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../inference/backends/persona_scheduler.rs | 16 ++- .../backends/persona_scheduler/driver.rs | 33 +++++-- .../backends/persona_scheduler/geometry.rs | 97 +++++++++++++++++++ core/llama/src/safe/expert_eval_cb.rs | 10 ++ 4 files changed, 145 insertions(+), 11 deletions(-) create mode 100644 core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index dd4b1e9236..030941859e 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -18,8 +18,11 @@ //! synchronous today), and paging cold minds out of RAM. mod driver; +mod geometry; mod sampling; +pub use geometry::{EngineGeometry, EngineState, Incarnation}; + use std::sync::Arc; use llama::{FlashAttn, KvCacheType, LoraAdapter, Model}; @@ -72,17 +75,26 @@ pub struct SchedulerConfig { #[derive(Clone)] pub struct Scheduler { request_tx: std::sync::mpsc::Sender, + state: tokio::sync::watch::Receiver, } impl Scheduler { /// Spawn the driver thread. It runs until the last handle is dropped and its last turn ended. pub fn spawn(model: Arc, config: SchedulerConfig) -> Result { let (request_tx, request_rx) = std::sync::mpsc::channel(); + let incarnation = Incarnation::next(); + let (state_tx, state) = tokio::sync::watch::channel(EngineState::Starting(incarnation)); std::thread::Builder::new() .name("persona-scheduler".to_string()) - .spawn(move || driver::run(&model, &config, &request_rx)) + .spawn(move || driver::run(&model, &config, driver::Start { incarnation, state: state_tx, requests: request_rx })) .map_err(|spawn| SchedulerError::Spawn(Arc::new(spawn)))?; - Ok(Self { request_tx }) + Ok(Self { request_tx, state }) + } + + /// The engine as it is: starting, the geometry its context applied, or why it was refused. The + /// one place serving reads the window, the batch and the KV layout from. + pub fn state(&self) -> tokio::sync::watch::Receiver { + self.state.clone() } /// Enqueue a turn. Refused once the driver thread has exited. diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs index 649b3e65c3..5cc5c7a0e1 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -15,7 +15,7 @@ use continuum_persona_llama::{Genes, Step, UnifiedTier, STREAMS}; use llama::{ContextParams, LoraAdapter, Model}; use uuid::Uuid; -use super::{sampling, GenerationRequest, SchedulerConfig, TokenEvent}; +use super::{sampling, EngineGeometry, EngineState, GenerationRequest, Incarnation, SchedulerConfig, TokenEvent}; use crate::inference::footprint_registry::{self, FootprintKey, ResourceType}; use crate::inference::kv_quant::Residency; use crate::runtime; @@ -86,29 +86,44 @@ struct Driver<'c, 'm> { parked: HashMap, } +/// What the driver thread starts with: the incarnation it serves as, where it publishes what the engine +/// is, and its one queue. +pub(super) struct Start { + pub(super) incarnation: Incarnation, + pub(super) state: tokio::sync::watch::Sender, + pub(super) requests: Receiver, +} + /// Run until every handle is dropped. -pub(super) fn run(model: &Model, config: &SchedulerConfig, requests: &Receiver) { +pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { let log = runtime::logger("persona-scheduler"); + let Start { incarnation, state, requests } = start; + let refuse = |refused: &StartError| { + log.error(&refused.to_string()); + state.send_replace(EngineState::Refused { incarnation, reason: refused.to_string().into() }); + }; let mut ctx = match context(model, config) { Ok(ctx) => ctx, Err(refused) => { - log.error(&refused.to_string()); - for req in requests { + refuse(&refused); + for req in &requests { let _ = req.response_tx.send(TokenEvent::Error(refused.to_string())); } return; } }; - let Some(batch) = usize::try_from(config.n_batch).ok().and_then(NonZeroUsize::new) else { - log.error(&StartError::ZeroBatch.to_string()); - for req in requests { + let Some(batch) = usize::try_from(ctx.n_batch()).ok().and_then(NonZeroUsize::new) else { + refuse(&StartError::ZeroBatch); + for req in &requests { let _ = req.response_tx.send(TokenEvent::Error(StartError::ZeroBatch.to_string())); } return; }; - log.info(&format!("persona scheduler ready (n_ctx={}, streams={STREAMS}, one mind decodes at a time)", config.n_ctx)); + let geometry = EngineGeometry::applied(incarnation, &ctx, config); + log.info(&format!("persona scheduler ready: {geometry:?} (one mind decodes at a time)")); + state.send_replace(EngineState::Ready(geometry)); let mut driver = Driver { model, batch, engine: PersonaEngine::new(UnifiedTier::new(&mut ctx)), parked: HashMap::new() }; - for req in requests { + for req in &requests { let respond = req.response_tx.clone(); let event = match driver.serve(req) { Ok(done) => done, diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs new file mode 100644 index 0000000000..f708b55016 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs @@ -0,0 +1,97 @@ +//! What the engine actually is, read from the context it created (never from what was asked): the +//! one owner serving reads for the window, the batch and the KV layout. Each snapshot names the +//! engine incarnation it was read from, so a reader retires a stale observation instead of acting +//! on an engine that is gone. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +use continuum_persona_llama::STREAMS; +use llama::{FlashAttn, KvCacheType}; + +use super::SchedulerConfig; + +/// Which engine a snapshot came from: one per scheduler spawn in this process, rising. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Incarnation(u64); + +impl Incarnation { + pub(super) fn next() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(1); + Self(NEXT.fetch_add(1, Ordering::Relaxed)) + } + + pub fn get(self) -> u64 { + self.0 + } +} + +/// The applied geometry of one engine. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EngineGeometry { + pub incarnation: Incarnation, + /// The window the context holds, across every stream. + pub n_ctx: u32, + pub n_batch: u32, + pub n_ubatch: u32, + /// Minds that decode at once: always one (one mind decodes at a time). + pub decoding: usize, + /// Windows held beside the decoding one for the next mind, staged as data, never decoding. + pub staging: usize, + pub type_k: KvCacheType, + pub type_v: KvCacheType, + pub flash_attn: FlashAttn, +} + +impl EngineGeometry { + /// Read from the created context. The KV types and attention are what the context was made + /// with; llama.cpp reports the window and batches it applied. + pub(super) fn applied(incarnation: Incarnation, ctx: &llama::Context<'_>, config: &SchedulerConfig) -> Self { + Self { + incarnation, + n_ctx: ctx.n_ctx(), + n_batch: ctx.n_batch(), + n_ubatch: ctx.n_ubatch(), + decoding: 1, + staging: STREAMS - 1, + type_k: config.type_k, + type_v: config.type_v, + flash_attn: config.flash_attn, + } + } +} + +/// The engine as serving sees it. +#[derive(Debug, Clone)] +pub enum EngineState { + /// Spawned; its context is not made yet. + Starting(Incarnation), + /// Its context is made: this is what it is. + Ready(EngineGeometry), + /// Its context was refused; no turn runs on this incarnation. + Refused { incarnation: Incarnation, reason: Arc }, +} + +impl EngineState { + pub fn incarnation(&self) -> Incarnation { + match self { + Self::Starting(incarnation) | Self::Refused { incarnation, .. } => *incarnation, + Self::Ready(geometry) => geometry.incarnation, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: two engines in one process sharing an incarnation, so serving cannot tell + // a snapshot of the engine that is gone from one of the engine that replaced it. + #[test] + fn each_engine_spawn_is_a_later_incarnation() { + let first = Incarnation::next(); + let second = Incarnation::next(); + assert!(second > first); + assert_eq!(EngineState::Starting(second).incarnation(), second); + } +} diff --git a/core/llama/src/safe/expert_eval_cb.rs b/core/llama/src/safe/expert_eval_cb.rs index 945eaee62a..096cd6a993 100644 --- a/core/llama/src/safe/expert_eval_cb.rs +++ b/core/llama/src/safe/expert_eval_cb.rs @@ -169,6 +169,16 @@ impl<'m> Context<'m> { unsafe { sys::llama_n_ctx(self.ptr.as_ptr()) } } + /// The logical batch the context was created with (llama.cpp may clamp what was asked). + pub fn n_batch(&self) -> u32 { + unsafe { sys::llama_n_batch(self.ptr.as_ptr()) } + } + + /// The physical micro-batch the context was created with. + pub fn n_ubatch(&self) -> u32 { + unsafe { sys::llama_n_ubatch(self.ptr.as_ptr()) } + } + /// Bytes llama.cpp has actually committed to the KV cache for the given /// sequence id. The honest source of truth for per-seq KV size — works /// across any model architecture (uniform attention, hybrid attention+SSM From 948858c2c1191305145f86d29c7d51bfd2843573 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 15:19:12 -0600 Subject: [PATCH 2/2] persona scheduler geometry: per-mind window and sequences measured, requested settings kept apart, a gone driver says Stopped (Codex on #6150) - EngineGeometry gains n_ctx_seq (the window ONE mind may use, what serving publishes as her usable context) and n_seq_max, both read from the created context (llama_n_ctx_seq, llama_n_seq_max; llama crate Context::n_ctx_seq and n_seq_max). staging is n_seq_max - 1. - The KV types and flash attention move into Requested: llama.cpp does not report what it applied (flash attention may be Auto), so they are never presented as applied capability. - EngineState::Stopped(incarnation): a StopsOnExit guard owned by the driver thread turns a Starting or Ready it leaves into Stopped however the thread ends (last handle dropped, an early return, a panic unwinding it); a Refused keeps its reason. EngineState::ready() returns the geometry only while serving. Test: an exiting driver leaves Stopped, never a stale Ready, keeps a refusal, and a panic unwinding it does the same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../inference/backends/persona_scheduler.rs | 2 +- .../backends/persona_scheduler/driver.rs | 4 + .../backends/persona_scheduler/geometry.rs | 106 ++++++++++++++---- core/llama/src/safe/expert_eval_cb.rs | 10 ++ 4 files changed, 102 insertions(+), 20 deletions(-) diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index 030941859e..b5cc2ca141 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -21,7 +21,7 @@ mod driver; mod geometry; mod sampling; -pub use geometry::{EngineGeometry, EngineState, Incarnation}; +pub use geometry::{EngineGeometry, EngineState, Incarnation, Requested}; use std::sync::Arc; diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs index 5cc5c7a0e1..1e719d487a 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -15,6 +15,7 @@ use continuum_persona_llama::{Genes, Step, UnifiedTier, STREAMS}; use llama::{ContextParams, LoraAdapter, Model}; use uuid::Uuid; +use super::geometry::StopsOnExit; use super::{sampling, EngineGeometry, EngineState, GenerationRequest, Incarnation, SchedulerConfig, TokenEvent}; use crate::inference::footprint_registry::{self, FootprintKey, ResourceType}; use crate::inference::kv_quant::Residency; @@ -98,6 +99,9 @@ pub(super) struct Start { pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { let log = runtime::logger("persona-scheduler"); let Start { incarnation, state, requests } = start; + // However this thread ends (its last handle dropped, an early return, or a panic unwinding it), + // a Starting or Ready it leaves becomes Stopped: serving never grants turns to a gone engine. + let _stops = StopsOnExit { state: &state, incarnation }; let refuse = |refused: &StartError| { log.error(&refused.to_string()); state.send_replace(EngineState::Refused { incarnation, reason: refused.to_string().into() }); diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs index f708b55016..6cea79cc57 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/geometry.rs @@ -1,12 +1,11 @@ //! What the engine actually is, read from the context it created (never from what was asked): the -//! one owner serving reads for the window, the batch and the KV layout. Each snapshot names the -//! engine incarnation it was read from, so a reader retires a stale observation instead of acting -//! on an engine that is gone. +//! one owner serving reads for the window, the batch and the sequence layout. Each snapshot names +//! the engine incarnation it was read from, so a reader retires a stale observation instead of +//! acting on an engine that is gone, and a driver that exits (or panics) says so. use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; -use continuum_persona_llama::STREAMS; use llama::{FlashAttn, KvCacheType}; use super::SchedulerConfig; @@ -26,37 +25,49 @@ impl Incarnation { } } -/// The applied geometry of one engine. +/// Settings the context was ASKED for that llama.cpp does not report back: flash attention may be +/// `Auto` (resolved natively per backend), and the KV types are requests. Never read as applied +/// capability. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Requested { + pub type_k: KvCacheType, + pub type_v: KvCacheType, + pub flash_attn: FlashAttn, +} + +/// The applied geometry of one engine, as llama.cpp reports it from the created context. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EngineGeometry { pub incarnation: Incarnation, - /// The window the context holds, across every stream. + /// The window the context holds, across every sequence. pub n_ctx: u32, + /// The window ONE mind may use: what serving publishes as her usable context. + pub n_ctx_seq: u32, + /// Sequences the context holds: the decoding mind's and the staged ones. + pub n_seq_max: u32, pub n_batch: u32, pub n_ubatch: u32, /// Minds that decode at once: always one (one mind decodes at a time). - pub decoding: usize, - /// Windows held beside the decoding one for the next mind, staged as data, never decoding. - pub staging: usize, - pub type_k: KvCacheType, - pub type_v: KvCacheType, - pub flash_attn: FlashAttn, + pub decoding: u32, + /// Sequences held beside the decoding one for the next mind, staged as data, never decoding. + pub staging: u32, + pub requested: Requested, } impl EngineGeometry { - /// Read from the created context. The KV types and attention are what the context was made - /// with; llama.cpp reports the window and batches it applied. + /// Read from the created context; only what it cannot report comes from the request. pub(super) fn applied(incarnation: Incarnation, ctx: &llama::Context<'_>, config: &SchedulerConfig) -> Self { + let n_seq_max = ctx.n_seq_max(); Self { incarnation, n_ctx: ctx.n_ctx(), + n_ctx_seq: ctx.n_ctx_seq(), + n_seq_max, n_batch: ctx.n_batch(), n_ubatch: ctx.n_ubatch(), decoding: 1, - staging: STREAMS - 1, - type_k: config.type_k, - type_v: config.type_v, - flash_attn: config.flash_attn, + staging: n_seq_max.saturating_sub(1), + requested: Requested { type_k: config.type_k, type_v: config.type_v, flash_attn: config.flash_attn }, } } } @@ -70,15 +81,46 @@ pub enum EngineState { Ready(EngineGeometry), /// Its context was refused; no turn runs on this incarnation. Refused { incarnation: Incarnation, reason: Arc }, + /// Its driver has exited (its last handle dropped, or a panic unwound it): no turn runs on this + /// incarnation, and nothing it published before is current. + Stopped(Incarnation), } impl EngineState { pub fn incarnation(&self) -> Incarnation { match self { - Self::Starting(incarnation) | Self::Refused { incarnation, .. } => *incarnation, + Self::Starting(incarnation) | Self::Refused { incarnation, .. } | Self::Stopped(incarnation) => *incarnation, Self::Ready(geometry) => geometry.incarnation, } } + + /// The geometry, only while the engine is serving. + pub fn ready(&self) -> Option<&EngineGeometry> { + match self { + Self::Ready(geometry) => Some(geometry), + Self::Starting(_) | Self::Refused { .. } | Self::Stopped(_) => None, + } + } +} + +/// Owned by the driver thread: when it exits by any path, including a panic unwinding it, a +/// `Starting` or `Ready` it left behind becomes `Stopped`. A `Refused` keeps its reason. +pub(super) struct StopsOnExit<'s> { + pub(super) state: &'s tokio::sync::watch::Sender, + pub(super) incarnation: Incarnation, +} + +impl Drop for StopsOnExit<'_> { + fn drop(&mut self) { + let incarnation = self.incarnation; + self.state.send_if_modified(|state| match state { + EngineState::Starting(_) | EngineState::Ready(_) => { + *state = EngineState::Stopped(incarnation); + true + } + EngineState::Refused { .. } | EngineState::Stopped(_) => false, + }); + } } #[cfg(test)] @@ -94,4 +136,30 @@ mod tests { assert!(second > first); assert_eq!(EngineState::Starting(second).incarnation(), second); } + + // what this catches (Codex on #6150): a driver that exited or panicked leaving its last Ready + // in the watch, so serving grants turns to an engine that is gone; and a Refused reason + // overwritten on the way out. + #[test] + fn an_exiting_driver_leaves_stopped_never_a_stale_ready_and_keeps_a_refusal() { + let incarnation = Incarnation::next(); + let (state, seen) = tokio::sync::watch::channel(EngineState::Starting(incarnation)); + drop(StopsOnExit { state: &state, incarnation }); + assert!(matches!(*seen.borrow(), EngineState::Stopped(i) if i == incarnation)); + assert!(seen.borrow().ready().is_none()); + + let reason: Arc = "the context was refused".into(); + state.send_replace(EngineState::Refused { incarnation, reason }); + drop(StopsOnExit { state: &state, incarnation }); + assert!(matches!(&*seen.borrow(), EngineState::Refused { reason, .. } if &**reason == "the context was refused")); + + // A panic unwinding the driver drops the guard the same way. + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + state.send_replace(EngineState::Starting(incarnation)); + let _stops = StopsOnExit { state: &state, incarnation }; + panic!("the driver failed"); + })); + assert!(panicked.is_err()); + assert!(matches!(*seen.borrow(), EngineState::Stopped(_))); + } } diff --git a/core/llama/src/safe/expert_eval_cb.rs b/core/llama/src/safe/expert_eval_cb.rs index 096cd6a993..3c29af27db 100644 --- a/core/llama/src/safe/expert_eval_cb.rs +++ b/core/llama/src/safe/expert_eval_cb.rs @@ -179,6 +179,16 @@ impl<'m> Context<'m> { unsafe { sys::llama_n_ubatch(self.ptr.as_ptr()) } } + /// The window one sequence may use, as the context applied it. + pub fn n_ctx_seq(&self) -> u32 { + unsafe { sys::llama_n_ctx_seq(self.ptr.as_ptr()) } + } + + /// The sequences the context holds. + pub fn n_seq_max(&self) -> u32 { + unsafe { sys::llama_n_seq_max(self.ptr.as_ptr()) } + } + /// Bytes llama.cpp has actually committed to the KV cache for the given /// sequence id. The honest source of truth for per-seq KV size — works /// across any model architecture (uniform attention, hybrid attention+SSM