diff --git a/Cargo.lock b/Cargo.lock index d89523dfc7..8f8bb46c93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3220,6 +3220,7 @@ dependencies = [ "candle-nn", "continuum-base", "continuum-engine", + "continuum-flow", "continuum-host", "continuum-kernel", "continuum-process", @@ -3602,9 +3603,11 @@ dependencies = [ name = "continuum-persona-llama" version = "0.1.0" dependencies = [ + "continuum-base", "continuum-persona-engine", "llama", "thiserror 2.0.18", + "tracing", "uuid", ] diff --git a/core/continuum-base/src/lib.rs b/core/continuum-base/src/lib.rs index 231fe46607..b5089626bc 100644 --- a/core/continuum-base/src/lib.rs +++ b/core/continuum-base/src/lib.rs @@ -14,6 +14,7 @@ pub mod non_empty_list; pub mod non_empty_text; pub mod probe; pub mod probed; +pub mod probe_writes; pub mod repo_id; pub mod reserved_rooms; pub mod secrets; diff --git a/core/continuum-base/src/probe_writes.rs b/core/continuum-base/src/probe_writes.rs new file mode 100644 index 0000000000..c816080027 --- /dev/null +++ b/core/continuum-base/src/probe_writes.rs @@ -0,0 +1,43 @@ +//! How many probe records a log sink failed to write, process-wide. A sink never fails its caller +//! over a write it could not make (a probe is telemetry), so it counts the failure here instead of +//! dropping it silently, and a reader that claims records reached the log (a stop's settle) states +//! how many writes failed in its window (Codex on #6208 at 162fbe5fa7: "written" confirmed only +//! that the tracing callbacks returned). + +use std::sync::atomic::{AtomicU64, Ordering}; + +static FAILED: AtomicU64 = AtomicU64::new(0); + +/// A probe record a sink could not write (serialize, lock, write or flush). +pub fn count_failure() { + FAILED.fetch_add(1, Ordering::Relaxed); +} + +/// The failures counted so far, read at one moment. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Reading(u64); + +impl Reading { + pub fn now() -> Self { + Self(FAILED.load(Ordering::Relaxed)) + } + + /// Failures counted between `earlier` and this reading. + pub fn since(self, earlier: Self) -> u64 { + self.0.saturating_sub(earlier.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: a failed probe write that no later reading can see. + #[test] + fn a_counted_failure_shows_in_the_next_reading() { + let before = Reading::now(); + count_failure(); + assert!(Reading::now().since(before) >= 1); + assert_eq!(before.since(Reading::now()), 0, "an earlier reading never goes negative"); + } +} diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs index 3045436712..ca7e8fb597 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs @@ -276,7 +276,7 @@ let bound = std::time::Duration::from_secs(1500); let start = tokio::time::Instant::now(); let dispatched = super::until_act_stalls(start + bound, bound, None, async { - let _witness = crate::cognition::generation_drop::InFlight::arm("Eitan", None, None); + let _witness = crate::cognition::generation_drop::InFlight::arm("Eitan", None, None, None); std::future::pending::<()>().await }) .await; @@ -306,7 +306,7 @@ true } async fn contribute(&self, _ws: &Workspace) -> Option { - let _witness = crate::cognition::generation_drop::InFlight::arm("Eitan", None, None); + let _witness = crate::cognition::generation_drop::InFlight::arm("Eitan", None, None, None); std::future::pending().await } } @@ -376,7 +376,7 @@ let start = tokio::time::Instant::now(); let condemned = async { tokio::time::sleep(std::time::Duration::from_secs(120)).await }; let ended = super::until_act_stalls_or(start + bound, bound, None, async { - let _witness = crate::cognition::generation_drop::InFlight::arm("Eitan", None, None); + let _witness = crate::cognition::generation_drop::InFlight::arm("Eitan", None, None, None); std::future::pending::<()>().await }, condemned) .await; diff --git a/core/continuum-cognition/src/cognition/generation_drop.rs b/core/continuum-cognition/src/cognition/generation_drop.rs index 645e11914a..ee59343736 100644 --- a/core/continuum-cognition/src/cognition/generation_drop.rs +++ b/core/continuum-cognition/src/cognition/generation_drop.rs @@ -100,6 +100,8 @@ pub(crate) fn partial_from_chunks( /// receipt is written. pub(crate) struct InFlight { persona: String, + /// The adapter request this generation was submitted as: the id the engine's transitions carry. + request: Option, /// The bound this turn STATED for itself on the wire — her measured expectation with /// headroom ([`crate::inference::turn_bound::from_expectation`]). A generation dropped /// while still inside it was healthy work, and the bound that reaped it (an outer act @@ -117,6 +119,7 @@ impl InFlight { /// adapter, when this caller owns it. pub fn arm( persona: &str, + request: Option<&str>, turn_bound: Option, chunks: Option>, ) -> Self { @@ -125,6 +128,7 @@ impl InFlight { crate::cognition::llm_deliberation_faculty::admission_clock::note_dispatched(); Self { persona: persona.to_string(), + request: request.map(str::to_owned), turn_bound, started: Instant::now(), chunks, @@ -170,6 +174,7 @@ impl Drop for InFlight { let act = crate::cognition::llm_deliberation_faculty::admission_clock::current_act(); continuum_base::probe!( class = "persona.generation.dropped", + request = ?self.request, persona = %self.persona, turn = ?act.map(|a| a.turn), step = ?act.map(|a| a.step), diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs index 9be772f3fb..77c281a476 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -237,6 +237,7 @@ impl LlmDeliberationFaculty { // the chunks and reports `observed = false` rather than a false zero. let mut witness = crate::cognition::generation_drop::InFlight::arm( &self.persona_name, + Some(&request_id), turn_bound, None, ); @@ -252,6 +253,7 @@ impl LlmDeliberationFaculty { // healthy path — the accumulate still comes from the returned response. let mut witness = crate::cognition::generation_drop::InFlight::arm( &self.persona_name, + Some(&request_id), turn_bound, Some(receiver), ); diff --git a/core/continuum-cognition/src/cognition/request_replay.rs b/core/continuum-cognition/src/cognition/request_replay.rs index 16db201d0d..3209b41bdf 100644 --- a/core/continuum-cognition/src/cognition/request_replay.rs +++ b/core/continuum-cognition/src/cognition/request_replay.rs @@ -41,6 +41,26 @@ pub struct ReplayRequestParams { #[serde(default)] #[ts(optional)] pub tool_schema_override: Option, + /// Which mind the engine serves the replay as. `isolated` (the default) is a stranger with + /// no cached state; `resident` is the source persona herself, so her parked blocks are reused + /// as her next live turn would reuse them. Either way the replay's capture is owned by a + /// separate replay identity, so a replay never enters her history or her learning. + #[serde(default)] + pub identity: ReplayIdentity, +} + +/// Which mind the engine serves a replay as. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ReplayIdentity { + /// A fresh mind with nothing cached: a cold turn. + #[default] + Isolated, + /// The source persona's own mind: her parked blocks are reused as live. It changes her native + /// KV cache (and the checkpoint a stop saves from it), never her memory, history or learning. + /// Interleaving with her live loop is safe (one serial queue per mind, reuse checked against the + /// prompt) but spoils a measurement, so hold and despawn her first. + Resident, } #[derive(Debug, Clone, Serialize, Deserialize, TS, JsonSchema)] @@ -89,6 +109,8 @@ impl From<&TextGenerationResponse> for ReplayOutcome { pub struct ReplayRequestResult { /// Separate capture owner/cache identity. Inspect it with cognition/playback. pub replay_persona_id: String, + /// Which mind the engine served it as: `isolated` (cold) or `resident` (her own parked blocks). + pub identity: ReplayIdentity, /// Submission cursor; list this replay identity to inspect its terminal event. pub selected: String, pub source_persona_id: String, @@ -221,6 +243,8 @@ struct Provenance { model_from_response: bool, persona: Uuid, cursor: String, + /// Which mind the engine served the replay as. + identity: ReplayIdentity, } impl Provenance { @@ -281,13 +305,18 @@ fn prepare( let replay = Uuid::new_v4(); let room = Uuid::new_v4(); let request_id = Uuid::new_v4().to_string(); - // Fresh identity isolates KV ownership. Prompt/model/genome/sampling remain recorded. - request.persona_id = Some(replay.to_string()); + // The capture is always owned by the fresh replay identity, so a replay never enters her + // history or learning. The engine serves it as a stranger (cold) or as her own mind (warm). + let served_as = match p.identity { + ReplayIdentity::Isolated => replay, + ReplayIdentity::Resident => persona, + }; + request.persona_id = Some(served_as.to_string()); request.room_id = Some(room.to_string()); request.request_id = Some(request_id.clone()); request.provider = Some(p.provider.clone()); request.purpose = Some("cognition/replay-request".into()); - let provenance = Provenance { input_comparison, model_from_response, persona, cursor: p.selected.clone() }; + let provenance = Provenance { input_comparison, model_from_response, persona, cursor: p.selected.clone(), identity: p.identity }; Ok(Prepared { request, call: PromptCall { @@ -312,7 +341,7 @@ fn prepare( impl ActionCommand for CognitionReplayRequest { const NAME: &'static str = "cognition/replay-request"; const ACCESS: AccessLevel = AccessLevel::Privileged; - const DESCRIPTION: &'static str = "Rerun a captured model request with optional max_tokens override, hash-bound collapsed-receipt omission, or one named tool schema override, using an explicit provider and isolated cache identity. Records original provenance and new lifecycle; returns outcome comparison. Never dispatches tool calls or changes live persona memory. Fresh inference, not deterministic full-mind replay."; + const DESCRIPTION: &'static str = "Rerun a captured model request with optional max_tokens override, hash-bound collapsed-receipt omission, or one named tool schema override, using an explicit provider, served as a fresh mind (identity isolated, cold) or as the source persona herself (identity resident, her parked blocks reused); the capture is always owned by a separate replay identity. Records original provenance and new lifecycle; returns outcome comparison. Never dispatches tool calls or writes her memory, history or learning; a resident replay does change her native KV cache and the checkpoint a stop saves from it, so a measuring run snapshots and restores her preserved blocks. Fresh inference, not deterministic full-mind replay."; type Params = ReplayRequestParams; type Output = ReplayRequestResult; @@ -383,6 +412,7 @@ async fn execute( capture.finish(Some(&response), None); Ok(ReplayRequestResult { replay_persona_id: replay_persona.to_string(), + identity: provenance.identity, selected, source_persona_id: provenance.persona.to_string(), source_selected: provenance.cursor, @@ -465,6 +495,7 @@ mod tests { omit_message_indices: Vec::new(), expected_request_sha256: None, tool_schema_override: None, + identity: ReplayIdentity::Isolated, }; let read = || prompt_capture::detail(dir.path(), persona, &cursor).expect("original capture"); @@ -490,6 +521,13 @@ mod tests { "all prompt/model/genome/sampling fields stay captured" ); assert_eq!(prepared.original_max_tokens, Some(16_384)); + // what this catches: a resident replay served as a stranger (cold, unlike her live turn), or + // its capture written as hers (a replay entering her history and learning). + let resident = ReplayRequestParams { identity: ReplayIdentity::Resident, ..p.clone() }; + let served = prepare(read(), &resident, persona).expect("prepare resident replay"); + assert_eq!(served.request.persona_id.as_deref(), Some(persona.to_string().as_str()), "a resident replay is served as her own mind"); + assert_ne!(served.call.persona_id, persona, "its capture is still owned by a separate replay identity"); + assert_eq!(served.provenance.identity, ReplayIdentity::Resident); // A diagnostic changes only named historical pointers, never tool protocol or settings. let mut diagnostic = request.clone(); let wm = crate::cognition::working_memory::WorkingMemory::new(8); diff --git a/core/continuum-core/tests/llamacpp_metal_throughput.rs b/core/continuum-core/tests/llamacpp_metal_throughput.rs index d999263993..38e00a5b14 100644 --- a/core/continuum-core/tests/llamacpp_metal_throughput.rs +++ b/core/continuum-core/tests/llamacpp_metal_throughput.rs @@ -22,7 +22,7 @@ //! Marked #[ignore] because it requires the qwen3.5-4b GGUF file at the DMR //! path, takes 10-30s, and isn't part of the regular CI test loop. -use continuum_core::inference::backends::llamacpp::GenerationAllocation; +use continuum_core::inference::backends::llamacpp::{GenerationAllocation, TurnPrompt}; use continuum_core::inference::backends::llamacpp::{LlamaCppBackend, LlamaCppConfig}; use continuum_core::inference::backends::SamplingConfig; use llama::FlashAttn; @@ -80,9 +80,9 @@ fn qwen35_08b_draft_path() -> Option { None } -#[test] +#[tokio::test] #[ignore = "requires local GGUF + 10-30s; run manually with --ignored --nocapture"] -fn qwen35_4b_metal_throughput_via_bundled_llamacpp() { +async fn qwen35_4b_metal_throughput_via_bundled_llamacpp() { let model_path = qwen35_4b_target_path(); if !model_path.exists() { panic!( @@ -129,7 +129,13 @@ fn qwen35_4b_metal_throughput_via_bundled_llamacpp() { eprintln!("[smoke] warm-up generation (10 tokens)..."); let warm_start = Instant::now(); let warm_result = backend - .generate(GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), "Reply OK.", 10, SamplingConfig::chat(), &[], &[]) + .submit_for_persona( + GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), + None, + TurnPrompt { text: "Reply OK.", stable_prefix: None, request: None }, 10, SamplingConfig::chat(), &[], &[]) + .expect("submit test turn") + .collect() + .await .expect("warm-up generate failed"); eprintln!( "[smoke] warm-up: {} tokens in {}ms ({:.1} tok/s) — text={:?}", @@ -143,13 +149,18 @@ fn qwen35_4b_metal_throughput_via_bundled_llamacpp() { eprintln!("[smoke] measurement generation (100 tokens)..."); let gen_start = Instant::now(); let (text, tokens) = backend - .generate(GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), - "Count from 1 to 50, separated by commas.", + .submit_for_persona( + GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), + None, + TurnPrompt { text: "Count from 1 to 50, separated by commas.", stable_prefix: None, request: None }, 100, SamplingConfig::chat(), &[], &[], ) + .expect("submit test turn") + .collect() + .await .expect("measurement generate failed"); let elapsed_secs = gen_start.elapsed().as_secs_f64(); let tokens_per_sec = tokens as f64 / elapsed_secs; diff --git a/core/continuum-core/tests/qwen35_chat_pipeline_full.rs b/core/continuum-core/tests/qwen35_chat_pipeline_full.rs index 3615420059..27c8409e2b 100644 --- a/core/continuum-core/tests/qwen35_chat_pipeline_full.rs +++ b/core/continuum-core/tests/qwen35_chat_pipeline_full.rs @@ -17,7 +17,7 @@ // unit tests are the windows-supported surface today. #![cfg(unix)] -use continuum_core::inference::backends::llamacpp::GenerationAllocation; +use continuum_core::inference::backends::llamacpp::{GenerationAllocation, TurnPrompt}; use continuum_core::inference::backends::llamacpp::{LlamaCppBackend, LlamaCppConfig}; use continuum_core::inference::backends::{SamplingConfig, JSON_GRAMMAR}; use llama::{render_chat, ChatMsg, FlashAttn}; @@ -33,9 +33,9 @@ fn model_path() -> std::path::PathBuf { const CHATML: &str = "{% for message in messages %}{{ '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"; -#[test] +#[tokio::test] #[ignore = "requires local GGUF; cargo test --release --test qwen35_chat_pipeline_full -- --ignored --nocapture"] -fn qwen35_persona_style_chat_produces_coherent_short_reply() { +async fn qwen35_persona_style_chat_produces_coherent_short_reply() { // n_gpu_layers honors QWEN35_N_GPU_LAYERS env var (default -1 = all on GPU). // Set QWEN35_N_GPU_LAYERS=0 for CPU-only inference. Needed on Intel Macs // with discrete AMD Metal devices where the SSM-hybrid qwen35 Metal @@ -93,7 +93,13 @@ fn qwen35_persona_style_chat_produces_coherent_short_reply() { // model produced correct '12 × 7 = 84' inside but never // reached the visible-text phase before max_tokens. let (text, n_tokens) = backend - .generate(GenerationAllocation::new(std::num::NonZeroU32::new(context_length).expect("explicit test allocation")), &prompt, 2500, sampling, &stop, &[]) + .submit_for_persona( + GenerationAllocation::new(std::num::NonZeroU32::new(context_length).expect("explicit test allocation")), + None, + TurnPrompt { text: &prompt, stable_prefix: None, request: None }, 2500, sampling, &stop, &[]) + .expect("submit test turn") + .collect() + .await .expect("generate"); eprintln!("[full] tokens={n_tokens} text={text:?}"); @@ -127,9 +133,9 @@ fn qwen35_persona_style_chat_produces_coherent_short_reply() { ); } -#[test] +#[tokio::test] #[ignore = "requires local GGUF; cargo test --release --test qwen35_chat_pipeline_full -- --ignored --nocapture"] -fn qwen35_scheduler_json_grammar_returns_object() { +async fn qwen35_scheduler_json_grammar_returns_object() { let backend = LlamaCppBackend::load(LlamaCppConfig { model_path: PathBuf::from(model_path()), n_gpu_layers: -1, @@ -160,13 +166,18 @@ fn qwen35_scheduler_json_grammar_returns_object() { }; let (text, n_tokens) = backend - .generate(GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), - &prompt, + .submit_for_persona( + GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), + None, + TurnPrompt { text: &prompt, stable_prefix: None, request: None }, 128, sampling, &["<|im_end|>", "<|endoftext|>"], &[], ) + .expect("submit test turn") + .collect() + .await .expect("generate"); eprintln!("[json-grammar] tokens={n_tokens} text={text:?}"); diff --git a/core/continuum-engine/src/inference/backends/llamacpp.rs b/core/continuum-engine/src/inference/backends/llamacpp.rs index 49c4862d6c..ca1bcbec7b 100644 --- a/core/continuum-engine/src/inference/backends/llamacpp.rs +++ b/core/continuum-engine/src/inference/backends/llamacpp.rs @@ -23,7 +23,7 @@ use crate::runtime; mod validate_embedding_model; pub use validate_embedding_model::*; mod llama_cpp_backend; -pub use llama_cpp_backend::TurnPrompt; +pub use llama_cpp_backend::{TurnAnswer, TurnPrompt}; mod embedding_lane; mod embedding_batch; pub(crate) use embedding_batch::{ContextBytes, EmbedWindow, EmbeddingBatch, NO_TRAINED_CONTEXT}; diff --git a/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs b/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs index e0b8748a77..3d8e340be2 100644 --- a/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs +++ b/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs @@ -6,6 +6,8 @@ use super::*; pub struct TurnPrompt<'a> { pub text: &'a str, pub stable_prefix: Option<&'a str>, + /// The submitted request's id, carried into the engine's transitions. + pub request: Option<&'a str>, } #[derive(Debug, thiserror::Error)] @@ -325,7 +327,7 @@ impl LlamaCppBackend { start.elapsed().as_millis() )); - // Sample-until-done loop. Mirrors LlamaCppBackend::generate but + // Sample-until-done loop. Uses the native sampler and // single-seq, no scheduler. EOG / max_tokens / stop-sequence are // the three exit conditions, same shape. let mut sampler = if sampling.temperature <= 0.0 && sampling.grammar.is_none() { @@ -500,49 +502,8 @@ impl LlamaCppBackend { Ok(self.scheduler(allocation)?.state()) } - /// Generate text through the persona scheduler: the turn continues her mind (one decodes at a - /// time, the next waits its turn) and tokens stream back as they are sampled. Concurrent - /// generate() calls are served one after another on the one context. - /// - /// `active_loras` is `(id, scale)` pairs naming genes previously paged - /// in via [`ensure_adapter`]. They are resolved to live adapter handles - /// and applied context-level by the scheduler before decode (genome - /// paging). A requested id that was never `ensure_adapter`'d is a hard - /// error — never a silent base-model run (Rule 2: fail loud). - pub fn generate( - &self, - allocation: GenerationAllocation, - prompt: &str, - max_tokens: usize, - sampling: SamplingConfig, - stop_sequences: &[&str], - active_loras: &[(String, f32)], - ) -> Result<(String, usize), String> { - // Forwards to the persona-aware variant with persona_id=None so - // test rigs and ad-hoc probes don't need to change. Production - // adapter calls go through generate_for_persona() so the registry - // can attribute KV bytes per-persona. - self.generate_for_persona( - allocation, - None, - TurnPrompt { text: prompt, stable_prefix: None }, - max_tokens, - sampling, - stop_sequences, - active_loras, - ) - } - - /// Same as `generate` but threads a `persona_id` through to the - /// scheduler so the registry can attribute the seq slot's KV bytes - /// to the right persona. Pass `None` for test/ad-hoc paths that - /// shouldn't appear in per-persona accounting. - /// - /// `persona_id` is forwarded as-is into `ActiveSeq::persona_id`. The - /// actual registry reporting (Piece 2 of the substrate work) hooks - /// into seq alloc / Done events inside the scheduler — this method's - /// only job here is to deliver the value. - pub fn generate_for_persona( + /// Prepare and enqueue on a blocking worker. The caller owns the returned event receiver. + pub fn submit_for_persona( &self, allocation: GenerationAllocation, persona_id: Option, @@ -551,14 +512,13 @@ impl LlamaCppBackend { sampling: SamplingConfig, stop_sequences: &[&str], active_loras: &[(String, f32)], - ) -> Result<(String, usize), String> { - let log = runtime::logger("llamacpp"); + ) -> Result { let gen_start = Instant::now(); let prompt = turn.text; let prompt_len_chars = prompt.len(); // Channel for streaming tokens back from the scheduler. - let (response_tx, mut response_rx) = tokio::sync::mpsc::unbounded_channel::(); + let (response_tx, response_rx) = tokio::sync::mpsc::unbounded_channel::(); // Resolve requested genes (`id`, scale) to live adapter handles from // the cache BEFORE crossing to the scheduler thread (which can't lock @@ -596,6 +556,7 @@ impl LlamaCppBackend { // top_k/top_p/repeat_penalty fields with no-op defaults. // Tokenized here, on this act's own thread, so the engine thread never tokenizes. let (prompt, view_end) = super::super::persona_scheduler::prepare(&self.model, prompt, turn.stable_prefix)?; + let prompt_tokens = prompt.len(); let req = GenerationRequest { prompt, view_end, @@ -605,46 +566,39 @@ impl LlamaCppBackend { active_loras: resolved_loras, response_tx, persona_id, + request: turn.request.map(super::super::persona_scheduler::RequestId::new), + submitted: Instant::now(), }; if let Err(refused) = self.scheduler(allocation)?.enqueue(req) { return Err(refused.to_string()); } + continuum_base::probe!( + class = "persona.engine.enqueued", + request = ?turn.request, + persona = ?persona_id, + prompt_tokens = prompt_tokens, + since_submit = ?gen_start.elapsed(), + "a turn was handed to the scheduler" + ); + + Ok(TurnAnswer { events: response_rx, started: gen_start, prompt_chars: prompt_len_chars, stops: stop_sequences.iter().map(|s| s.to_string()).collect() }) + } +} - // Collect tokens from the channel until Done/Error. We're called - // synchronously from spawn_blocking by CandleAdapter — block_in_place - // a tokio runtime handle to await the channel. - // - // Stop-sequence trimming happens here (at the boundary): the - // scheduler emits the stop sequence's tokens before signaling Done, - // so we strip them from the collected output. - let mut output = String::new(); - let runtime_handle = tokio::runtime::Handle::try_current().ok(); +/// Dropping a turn drops its receiver even when the native driver is busy. +pub struct TurnAnswer { + events: tokio::sync::mpsc::UnboundedReceiver, + started: Instant, + prompt_chars: usize, + stops: Vec, +} +impl TurnAnswer { + pub async fn collect(mut self) -> Result<(String, usize), String> { + let mut output = String::new(); loop { - let event = if let Some(ref h) = runtime_handle { - h.block_on(response_rx.recv()) - } else { - // Fallback for non-tokio callers (e.g. tests). Spin briefly. - let mut tries = 0u32; - loop { - match response_rx.try_recv() { - Ok(e) => break Some(e), - Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => { - break None; - } - Err(tokio::sync::mpsc::error::TryRecvError::Empty) => { - std::thread::sleep(std::time::Duration::from_millis(2)); - tries += 1; - if tries > 60_000 { - // 2 minutes without a token — treat as fatal. - break None; - } - } - } - } - }; - match event { + match self.events.recv().await { Some(TokenEvent::Token(piece)) => { output.push_str(&piece); } @@ -655,19 +609,19 @@ impl LlamaCppBackend { // The scheduler's own count is the receipt; a per-piece tally here // was never read (rustc: value assigned is never read). let n_decoded = tokens_generated; - let elapsed = gen_start.elapsed(); - log.info(&format!( + let elapsed = self.started.elapsed(); + runtime::logger("llamacpp").info(&format!( "Generated {} tokens in {:.3}s ({:.1} tok/s, scheduler={}ms, prompt={}chars)", n_decoded, elapsed.as_secs_f64(), n_decoded as f64 / elapsed.as_secs_f64().max(0.001), elapsed_ms, - prompt_len_chars + self.prompt_chars )); // Trim trailing stop sequence(s) — scheduler emits them // before signaling Done. - for s in stop_sequences { - if output.ends_with(s) { + for s in &self.stops { + if output.ends_with(s.as_str()) { output.truncate(output.len() - s.len()); } } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index 4055c9d435..638f1010bc 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -25,9 +25,29 @@ mod frame; mod reuse; mod geometry; mod sampling; +mod admission; +mod transition; pub use geometry::{EngineGeometry, EngineState, Incarnation, Requested}; +/// A submitted generation request's identity (the adapter request's `request_id`), the one id that +/// crosses from her deliberation into the engine. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RequestId(Arc); + +impl RequestId { + #[must_use] + pub fn new(id: &str) -> Self { + Self(Arc::from(id)) + } + + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } +} + + use std::sync::Arc; use llama::{KvCacheType, LoraAdapter, Model}; @@ -81,6 +101,11 @@ pub struct GenerationRequest { /// The persona whose mind this turn continues. `None` is a one-off (a probe, a test rig): it /// runs as a mind of its own and its blocks are released when the turn ends. pub persona_id: Option, + /// The submitted request's identity, carried through every transition this turn reports, so a + /// stall says how far it got. `None` when the caller sent none. + pub request: Option, + /// When the turn was handed to the scheduler, so the driver's admission reports how long it waited. + pub submitted: std::time::Instant, } /// The context the scheduler creates. Its window holds [`continuum_persona_llama::STREAMS`] minds' @@ -105,10 +130,33 @@ pub(super) enum Submission { Suspend(tokio::sync::oneshot::Sender), } +/// What a stop can say about the records of the turns it ended. The record stage confirms it +/// processed them, in order, into the log; whether each line reached disk is the log sink's, so a +/// settle reports the sink's failed writes in its window instead of claiming them written (Codex on +/// #6208 at 162fbe5fa7). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Records { + /// Every record sent before the stop was processed into the log; `write_failures` counts the + /// probe-log writes that failed since the previous settle (0: none reported). + Processed { write_failures: u64 }, + /// The record stage ended before confirming them: they may be lost. + Unconfirmed, +} + +impl Default for Records { + /// A stop that ended no turns: nothing to lose. + fn default() -> Self { + Self::Processed { write_failures: 0 } + } +} + /// What a suspend preserved (CONTINUUM-ENGINE 4.16): how many minds it published, and every mind it /// could not preserve, with why. A mind it could not preserve is held only by the live process. #[derive(Debug, Clone, Default)] pub struct Suspended { + /// Whether the records of the turns this stop ended were confirmed written: telemetry, so it + /// never changes custody, and a stop that preserved every mind says so even when it is not. + pub records: Records, pub preserved: usize, pub retained: Vec<(Uuid, String)>, } @@ -124,6 +172,16 @@ pub struct Scheduler { /// The engine the stop suspends: the last one spawned in this process. static SUSPENDS: std::sync::Mutex>> = std::sync::Mutex::new(None); +/// What a stop's report adds about its turns' records: nothing when processed with no failed write. +fn records_note(records: Records) -> String { + match records { + Records::Processed { write_failures: 0 } => String::new(), + Records::Processed { write_failures } => format!("; {write_failures} probe-log writes failed since the last stop, so some turn records may not be on disk"), + Records::Unconfirmed => "; the records of the turns it ended were not confirmed processed".into(), + } +} + + /// The engine's part in a stop (CONTINUUM-ENGINE 4.16, Codex on 2990b44831): its root suspend, /// through the kernel's `SettleBeforeStop`, before native contexts are released. Each mind leaves the /// stream through the pipeline and is written; the manifest is the commit point. A mind not preserved @@ -147,10 +205,12 @@ impl crate::runtime::extensions::SettleBeforeStop for EngineSettle { return Vec::new(); // the engine already ended, and with it every mind it held } match tokio::time::timeout(cap, suspended).await { + // Records are telemetry: unconfirmed ones never change custody, and the report says so. Ok(Ok(suspended)) if suspended.retained.is_empty() => { - vec![crate::runtime::HeldCustody { endpoint: format!("persona_engine: {} minds preserved", suspended.preserved), process: None, state: crate::runtime::CustodyState::Saved }] + let endpoint = format!("persona_engine: {} minds preserved{}", suspended.preserved, records_note(suspended.records)); + vec![crate::runtime::HeldCustody { endpoint, process: None, state: crate::runtime::CustodyState::Saved }] } - Ok(Ok(suspended)) => held(&format!("{} minds not preserved: {:?}", suspended.retained.len(), suspended.retained)), + Ok(Ok(suspended)) => held(&format!("{} minds not preserved: {:?}{}", suspended.retained.len(), suspended.retained, records_note(suspended.records))), Ok(Err(_)) => held("the engine ended before it reported its suspend"), Err(_) => held("the suspend did not finish within the stop's cap"), } @@ -183,9 +243,9 @@ impl Scheduler { .name("persona-scheduler".to_string()) .spawn(move || { driver::run(&model, &config, driver::Start { incarnation, state: state_tx, requests: request_rx, emit, record, stages_on: runtime.clone() }); - emit_worker.stop(); - record_worker.stop(); - let (emit, record) = runtime.block_on(async { tokio::join!(emit_worker.join(), record_worker.join()) }); + // No stop: the stages end once their last producer is gone and they have drained, so + // answer ends a closing driver handed to its drain owner still reach their callers. + let (emit, record) = runtime.block_on(driver::finish(emit_worker, record_worker)); for failure in [emit, record].into_iter().filter_map(Result::err) { tracing::error!(%failure, "persona stage failed at shutdown"); } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/admission.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/admission.rs new file mode 100644 index 0000000000..6088e7eeb5 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/admission.rs @@ -0,0 +1,48 @@ +//! Whether a turn fits the Core at all, decided at the door (object model §3.8: the Core answers +//! `Infeasible` when a need exceeds its cap, with the numbers). +//! +//! The M5, 2026-11-21: a 26,633-token replay prompt was admitted to a 24,576-token stream, prefilled +//! for ~31 s, and refused by the engine at the boundary chunk ("no KV slot"). A turn whose prompt +//! leaves no room for even one generated token is refused before any work is spent on it. + +/// The most tokens one mind's stream holds: the applied geometry's `n_ctx_seq`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct StreamCapacity(usize); + +/// A turn that cannot fit this Core, with the numbers. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("her prompt is {prompt_tokens} tokens and one stream holds {capacity}: no room to answer on this engine")] +pub(super) struct Infeasible { + pub prompt_tokens: usize, + pub capacity: usize, +} + +impl StreamCapacity { + pub(super) const fn new(tokens: usize) -> Self { + Self(tokens) + } + + /// Admit a prompt only if it leaves room for at least one generated token. + pub(super) const fn admit(self, prompt_tokens: usize) -> Result<(), Infeasible> { + if prompt_tokens < self.0 { + Ok(()) + } else { + Err(Infeasible { prompt_tokens, capacity: self.0 }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: a prompt that cannot fit the stream admitted and failing deep in prefill + // (the 2026-11-21 replay), and a prompt that fits refused at the edge. + #[test] + fn a_prompt_is_admitted_only_with_room_for_one_token() { + let stream = StreamCapacity::new(24_576); + assert_eq!(stream.admit(24_575), Ok(()), "one token of room is enough to start"); + assert_eq!(stream.admit(24_576), Err(Infeasible { prompt_tokens: 24_576, capacity: 24_576 })); + assert_eq!(stream.admit(26_633), Err(Infeasible { prompt_tokens: 26_633, capacity: 24_576 })); + } +} 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 c302664b9f..e68ec8dced 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -1,7 +1,7 @@ //! The driver thread: a frame loop over one context (CONTINUUM-ENGINE 4.15). Each frame advances one //! turn by one step, so no mind waits behind another's whole prompt; one mind decodes at a time. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::num::NonZeroUsize; use tokio::sync::mpsc::UnboundedReceiver as Receiver; use std::sync::atomic::{AtomicBool, Ordering}; @@ -18,7 +18,7 @@ use uuid::Uuid; use super::geometry::StopsOnExit; use continuum_flow::{Outbox, StageInput}; -use super::{emit, frame, preserve, record, reuse, sampling, EngineGeometry, EngineState, GenerationRequest, Incarnation, SchedulerConfig, Submission, Suspended, TokenEvent}; +use super::{admission, emit, frame, preserve, record, reuse, sampling, transition, EngineGeometry, EngineState, GenerationRequest, Incarnation, SchedulerConfig, Submission, Suspended, TokenEvent}; use crate::inference::footprint_registry::{self, FootprintKey, ResourceType}; use crate::inference::kv_quant::Residency; use crate::runtime; @@ -45,6 +45,8 @@ pub(super) enum TurnError { TooLong, #[error("nothing was decoded for her turn")] NothingDecoded, + #[error("the caller released this turn")] + CallerReleased, } /// Why one mind was not preserved at a stop. She stays in the engine's custody, and the stop @@ -92,36 +94,12 @@ enum Tenure { OneOff, } -/// The tokens her blocks hold, and her checkpoint at her last view's end while what she holds still -/// runs through it. -#[derive(Default)] -struct History { - held: Vec, - kept: [Option; 2], -} - -/// Her checkpoint and what makes it valid: she held exactly `held[..end]` under `basis` when it was -/// taken, and nothing she holds below `end` has changed since (a cut below it drops it). -struct KeptCheckpoint { - blocks: llama::PersonaCheckpoint, - end: usize, - basis: Basis, -} - -/// Her checkpoint holds her recurrent rows in host memory. -impl Footprint for KeptCheckpoint { - fn held(&self) -> Held { - Held::host(self.blocks.bytes() as u64) - } -} +mod ending; +mod history; -/// Her token history and her checkpoint. Her blocks in the context are reported by the tier that -/// binds them; [`Bound`] is that child's view. -impl Footprint for History { - fn held(&self) -> Held { - self.kept.iter().fold(self.held.held(), |bytes, kept| bytes + kept.held()) - } -} +use ending::{Ending, Stop, Suspension}; +pub(super) use ending::finish; +use history::{Boundary, History, Boundaries}; /// A bound mind's blocks, as the tier that holds them in the context reports them. struct Bound<'t, 'c, 'm> { @@ -135,28 +113,8 @@ impl Footprint for Bound<'_, '_, '_> { } } -impl History { - /// Keep only her first `len` tokens; a cut below her checkpoint's end drops the checkpoint. - fn cut(&mut self, len: usize) { - self.held.truncate(len); - for slot in &mut self.kept { - if slot.as_ref().is_some_and(|kept| kept.end > len) { - *slot = None; - } - } - } - - /// Where `prompt` under `basis` would start for her, whose blocks were computed under `under` - /// (`reuse::choose`), deciding nothing and moving nothing: the bind uses it to resume her, the - /// frame to size her turn's prefill. - fn reuse(&self, under: &Basis, prompt: &[i32], basis: &Basis) -> reuse::Reuse { - let kept = self.kept.iter().flatten().map(|kept| reuse::Kept { end: kept.end, basis: &kept.basis }); - reuse::choose(reuse::History { basis: under, tokens: &self.held }, kept, reuse::History { basis, tokens: prompt }) - } -} - /// Where `prompt` under `basis` would start for `her`. -fn reuse_for(her: &Mind, prompt: &[i32], basis: &Basis) -> reuse::Reuse { +fn reuse_for(her: &Mind, prompt: &[i32], basis: &Basis) -> reuse::Decision { her.parts().tokens.reuse(&her.parts().genome, prompt, basis) } @@ -168,13 +126,19 @@ fn resident(her: &Mind) -> bool { struct Driver<'c, 'm> { model: &'m Model, batch: NonZeroUsize, + /// The most one mind's stream holds (the applied `n_ctx_seq`): a prompt it cannot fit is refused at the door. + capacity: admission::StreamCapacity, engine: PersonaEngine>, parked: HashMap, + /// Admitted anonymous turns that still own their native blocks, across all transfer states. + live_one_offs: HashSet, /// Where decoded tokens and answer ends go (4.16); the engine thread never does text work. emit: Outbox, /// Where each GPU step's span and each finished turn's row go; measured and written off this /// thread. record: Outbox, + /// The probe-log write failures counted at the last settle: a stop reports those since. + log_failures: continuum_base::probe_writes::Reading, /// Answers opened by this engine, numbering each. answers: u64, /// Where the stop preserves minds and the start resumes them (`None`: this node has no home to @@ -212,7 +176,7 @@ fn resume(tier: &mut UnifiedTier<'_, '_>, preserved: &mut preserve::Preserved, m match tier.read_file(MindId { persona: id, epoch }, &preserved.path(&mind.blocks)) { Ok(blocks) => { continuum_base::probe!(class = "persona.engine.resumed", persona = %mind.persona, tokens = mind.held.len() as u64, "a mind came back from her preserved blocks"); - let parts = Parts { blocks, tokens: History { held: mind.held, kept: Default::default() }, genome: Basis { genes: mind.basis }, learning: (), decode: Tenure::Resident }; + let parts = Parts { blocks, tokens: History::from(mind.held), genome: Basis { genes: mind.basis }, learning: (), decode: Tenure::Resident }; parked.insert(id, Mind::new(id, epoch, parts)); } Err(refused) => { @@ -274,6 +238,7 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { return; }; let geometry = EngineGeometry::applied(incarnation, &ctx, config); + let capacity = admission::StreamCapacity::new(geometry.n_ctx_seq as usize); // The root resume (CONTINUUM-ENGINE 4.16): the minds the last stop preserved come back Warm, in // RAM, and bind when they are next scheduled. A mind that does not verify stays on disk, named. let mut tier = UnifiedTier::new(&mut ctx); @@ -290,17 +255,21 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { let mut driver = Driver { model, batch, + capacity, engine: PersonaEngine::new(tier), parked, + live_one_offs: HashSet::new(), emit: Outbox::new(emit), record: Outbox::new(record), + log_failures: continuum_base::probe_writes::Reading::now(), answers: 0, store: store.ok(), model_id: config.model.clone(), stopping: false, }; // The frame loop (CONTINUUM-ENGINE 4.15): submissions are drained without blocking, and each - // frame advances ONE turn by ONE step (a prefill chunk or a token), chosen by `frame::pick`. What + // frame advances ONE turn by ONE step (a prefill chunk or a token), chosen by `frame::pick`: a turn + // in progress keeps the Core until it ends, so new submissions wait for its end. What // it decodes goes to Emit (4.16) and the loop goes on. It blocks only when no turn is left, on // the queue itself: a wake, never a poll. let mut turns: Vec = Vec::new(); @@ -312,6 +281,9 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { // the stage's space: a wake on both, never a poll, and a stalled caller never blocks a stop. let holding = driver.holding(); if holding || turns.is_empty() { + let parked_at = Instant::now(); + let emit_pending = driver.emit.waiting(); + let record_pending = driver.record.waiting(); let woke = stages_on.block_on(async { tokio::select! { biased; @@ -319,28 +291,48 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { () = driver.drain(), if holding => None, } }); + let parked_for = parked_at.elapsed(); + if parked_for > std::time::Duration::from_millis(500) { + let wake = match &woke { + Some(Some(Submission::Turn(_))) => "turn", + Some(Some(Submission::Suspend(_))) => "suspend", + Some(None) => "closed", + None => "stage_space", + }; + continuum_base::probe!( + class = "persona.engine.park", + parked_ms = super::record::whole_ms(parked_for), + active_turns = turns.len() as u64, + emit_pending = emit_pending as u64, + record_pending = record_pending as u64, + wake = wake, + "engine thread resumed after parking" + ); + } match woke { - Some(Some(submission)) => driver.take(submission, &mut turns), - // Every handle dropped: Emit ends once it has drained what it holds. - Some(None) => return, + Some(Some(submission)) => { + if let Some(stop) = driver.take(submission, &mut turns) { + driver.acknowledge(stop, &stages_on); + } + } + // Every handle dropped: every admitted turn ends and its caller is told. + Some(None) => return driver.close(&mut turns, &stages_on), None => {} // the stages took what waited } continue; } while let Ok(submission) = requests.try_recv() { - driver.take(submission, &mut turns); + if let Some(stop) = driver.take(submission, &mut turns) { + driver.acknowledge(stop, &stages_on); + } } let Some(index) = driver.pick(&turns) else { continue }; match driver.step(&mut turns[index]) { Ok(Advanced::Continues) => {} - Ok(Advanced::Done(done)) => { - let turn = turns.remove(index); - driver.emit.send(emit::Out::End { answer: turn.answer, event: done }); - } + Ok(Advanced::Done { tokens_generated, elapsed_ms }) => driver.end(turns.remove(index), Ending::Answered { tokens_generated, elapsed_ms }), Err(refused) => { log.warn(&format!("turn refused: {refused}")); - let turn = turns.remove(index); - driver.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error(refused.to_string()) }); + driver.end(turns.remove(index), Ending::Refused(refused)); } } } @@ -359,10 +351,11 @@ struct Turn { sampler: llama::Sampler, phase: Phase, submitted: Instant, + ready_since: Instant, spent: Spent, /// Where her view ends in `prompt` (CONTINUUM-ENGINE 4.15): a prefill chunk ends exactly there /// and she is checkpointed, so her next act resumes from it. `None` for a turn with no view. - boundaries: [Option; 2], + boundaries: Boundaries, /// Her answer, as Emit numbers it. answer: emit::AnswerSeq, /// Raised by Emit when her answer has ended on a stop sequence or her caller hung up; read at @@ -373,7 +366,8 @@ struct Turn { /// Where a turn stands. enum Phase { /// Not bound yet: what her prefill starts from is decided against her blocks when she is. - Waiting, + /// Estimate once when first eligible, after any earlier turn for this mind. Native resume checks the actual blocks again. + Waiting(std::cell::OnceCell), /// Her prompt from `pos` is still to prefill. Prefilling { pos: usize }, /// `token` is sampled and not yet emitted; it is decoded at `pos` if she goes on. @@ -383,12 +377,15 @@ enum Phase { /// Where a turn's time went, for its one probe row. #[derive(Default)] struct Spent { + /// Her once-only transitions: first frame started, first native progress. + milestones: transition::Milestones, reused: usize, shared_prefix_tokens: usize, /// How her prefill started: append, rewind, or the restart's reason. start: &'static str, checkpoint_ms: u64, first_step: Option, + longest_gap: std::time::Duration, switch: std::time::Duration, prefill: std::time::Duration, decode: std::time::Duration, @@ -407,7 +404,8 @@ struct Spent { /// What a step did to its turn. enum Advanced { Continues, - Done(TokenEvent), + /// She answered: what her `TokenEvent::Done` will say. + Done { tokens_generated: usize, elapsed_ms: u64 }, } /// The one context: `STREAMS` sequences (the active mind's and the next one's). @@ -449,10 +447,10 @@ impl Driver<'_, '_> { self.record.flush(); } - /// Hand each stage everything that waits for it, awaiting its space: only when no turn is left. + /// Each outbox wakes on its own consumer's space. Both retain undelivered items + /// when an incoming submission interrupts the drain. async fn drain(&mut self) { - self.emit.drain().await; - self.record.drain().await; + tokio::join!(self.emit.drain(), self.record.drain()); } /// Whether anything still waits for a stage that was full. @@ -462,16 +460,19 @@ impl Driver<'_, '_> { /// Route what arrived: a turn into the frame loop (refused once the stop has suspended every /// mind), or the stop's suspend. - fn take(&mut self, submission: Submission, turns: &mut Vec) { + /// A stop is handed back, not acknowledged here: the loop writes its last records first. + #[must_use = "a stop must be acknowledged once its records are written"] + fn take(&mut self, submission: Submission, turns: &mut Vec) -> Option { match submission { Submission::Turn(req) if self.stopping => { tell(&req.response_tx, TokenEvent::Error("the engine is stopping: her minds are preserved, and her turn starts after it restarts".into())); + None } - Submission::Turn(req) => self.admit(req, turns), - Submission::Suspend(reply) => { - let suspended = self.suspend(turns); - report(reply, suspended); + Submission::Turn(req) => { + self.admit(req, turns); + None } + Submission::Suspend(reply) => Some(Stop { reply, suspension: self.suspend(turns) }), } } @@ -480,18 +481,29 @@ impl Driver<'_, '_> { /// checkpoint (so a restart resumes exactly at her view), retired through the pipeline, then her /// blocks and token history written. The manifest naming every preserved mind is published last: /// it is the commit point. A mind not preserved is reported, never silently dropped. - fn suspend(&mut self, turns: &mut Vec) -> Suspended { + fn suspend(&mut self, turns: &mut Vec) -> Suspension { self.stopping = true; - for turn in turns.drain(..) { - self.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error("the engine is stopping: her state is preserved".into()) }); + for turn in std::mem::take(turns) { + self.end(turn, Ending::Stopping); + } + let minds: Vec<_> = self.parked.values().chain(self.engine.units()) + .filter(|mind| resident(mind)).map(|mind| mind.id()).collect(); + let blocked = |cause: Uuid, why: String| { + let retained = if minds.is_empty() { + vec![(cause, why)] + } else { + minds.iter().map(|mind| (mind.0, why.clone())).collect() + }; + Suspension { preserved: 0, retained } + }; + if let Some(id) = self.engine.retiring() { + if let Err(why) = self.retire_previous() { + return blocked(id.0, format!("copy-out of {:?} blocked preservation: {why}", id.0)); + } } let Some(mut store) = self.store.take() else { - return Suspended { preserved: 0, retained: vec![(Uuid::nil(), "this node has no home to preserve minds in".into())] }; + return blocked(Uuid::nil(), "this node has no home to preserve minds in".into()); }; - let mut minds: Vec = self.parked.iter().filter(|(_, mind)| resident(mind)).map(|(id, _)| *id).collect(); - if let Some(active) = self.engine.active().filter(|id| self.engine.active_mut().is_some_and(|her| resident(her) && her.id() == *id)) { - minds.push(active); - } // This stop's generation: every mind's blocks go to a file no published manifest names, and the // manifest naming them is published only once every write has landed (preserve.rs). let generation = preserve::Generation::fresh(); @@ -515,14 +527,14 @@ impl Driver<'_, '_> { // the M5's first suspend, 2026-11-19 03:57Z) runtime::logger("persona-scheduler").info(&format!("the stop preserved {preserved} minds; not preserved: {retained:?}")); self.store = Some(store); - Suspended { preserved, retained } + Suspension { preserved, retained } } /// One mind out to her file in `generation`: bound, rewound to her view, retired through the /// pipeline, written. Her entry names that file; it is published with the stop's manifest. fn preserve(&mut self, id: PersonaId, store: &preserve::Preserved, generation: &preserve::Generation) -> Result { self.switch_to(id, false)?; - let end = self.engine.active_mut().and_then(|her| her.parts().tokens.kept.iter().flatten().map(|kept| kept.end).max()); + let end = self.engine.active_mut().and_then(|her| her.parts().tokens.deepest()); if let Some(end) = end { self.rewind_to_checkpoint(end)?; self.record(|her| her.tokens.cut(end))?; @@ -544,6 +556,14 @@ impl Driver<'_, '_> { Some(persona) => (PersonaId(persona), false), None => (PersonaId(Uuid::new_v4()), true), }; + // A prompt this Core's stream cannot hold is refused at the door, with the numbers, before + // any prefill is spent on it. + if let Err(infeasible) = self.capacity.admit(req.prompt.len()) { + let at = transition::At::Infeasible { prompt_tokens: infeasible.prompt_tokens, capacity: infeasible.capacity }; + self.record.send(record::Fact::Transition(transition::Transition { request: req.request.clone(), persona: id.0, one_off, at })); + tell(&req.response_tx, TokenEvent::Error(infeasible.to_string())); + return; + } // Her prompt arrives as token ids (`prepare`, on her own thread): nothing is tokenized here. match sampling::sampler(self.model, &req.sampling).map_err(TurnError::from) { Ok(sampler) => { @@ -555,7 +575,16 @@ impl Driver<'_, '_> { let answer = emit::AnswerSeq(self.answers); let cancel = Arc::new(AtomicBool::new(false)); self.emit.send(emit::Out::Open { answer, sink: req.response_tx.clone(), stops: req.stop_sequences.clone().into(), cancel: Arc::clone(&cancel) }); - turns.push(Turn { req, id, one_off, prompt, basis, genes, sampler, phase: Phase::Waiting, submitted: Instant::now(), spent: Spent::default(), boundaries: [boundary, None], answer, cancel }); + let submitted = Instant::now(); + if one_off { self.live_one_offs.insert(id); } + let admitted = transition::Transition { + request: req.request.clone(), + persona: id.0, + one_off, + at: transition::At::Admitted { queue_depth: turns.len() + 1, prompt_tokens: prompt.len(), since_submit_ms: record::whole_ms(req.submitted.elapsed()) }, + }; + turns.push(Turn { req, id, one_off, prompt, basis, genes, sampler, phase: Phase::Waiting(Default::default()), submitted, ready_since: submitted, spent: Spent::default(), boundaries: Boundaries { view: boundary, learned: None }, answer, cancel }); + self.record.send(record::Fact::Transition(admitted)); } Err(refused) => { tell(&req.response_tx, TokenEvent::Error(refused.to_string())); @@ -568,6 +597,11 @@ impl Driver<'_, '_> { /// cannot reuse, never her whole prompt: a 1.2k tail on a 29k prompt she holds is a 1.2k turn /// (the M5, 2026-11-19, a6da599330: sized as 29k, her rewind waited 161 s behind cold prompts). fn pick(&mut self, turns: &[Turn]) -> Option { + // A lone turn needs no ranking or cache estimate. Its bind still + // validates reuse against the actual prompt before advancing. + if turns.len() == 1 { + return Some(0); + } let mut seen = std::collections::HashSet::new(); let eligible: Vec = (0..turns.len()).filter(|&index| seen.insert(turns[index].id)).collect(); let active = self.engine.active(); @@ -575,17 +609,17 @@ impl Driver<'_, '_> { .iter() .map(|&index| { let turn = &turns[index]; - let (decoding, remaining) = match &turn.phase { - Phase::Waiting => { + let (started, remaining) = match &turn.phase { + Phase::Waiting(estimate) => (false, *estimate.get_or_init(|| { let her = if active == Some(turn.id) { self.engine.active_mut().map(|her| &*her) } else { self.parked.get(&turn.id) }; - let reused = if let Some(her) = her { reuse_for(her, &turn.prompt, &turn.basis).reused() } else { 0 }; // a mind never seen reuses nothing - (false, turn.prompt.len().saturating_sub(reused)) - } - Phase::Prefilling { pos } => (false, turn.prompt.len().saturating_sub(*pos)), + let reused = if let Some(her) = her { reuse_for(her, &turn.prompt, &turn.basis).action.reused() } else { 0 }; // a mind never seen reuses nothing + turn.prompt.len().saturating_sub(reused) + })), + Phase::Prefilling { pos } => (true, turn.prompt.len().saturating_sub(*pos)), Phase::Decoding { .. } => (true, 0), }; - let waited_ms = record::whole_ms(turn.submitted.elapsed()); - frame::Candidate { active: active == Some(turn.id), decoding, remaining, waited_ms } + let waited_ms = record::whole_ms(turn.ready_since.elapsed()); + frame::Candidate { active: active == Some(turn.id), started, remaining, waited_ms } }) .collect(); frame::pick(&candidates).map(|chosen| eligible[chosen]) @@ -594,6 +628,11 @@ impl Driver<'_, '_> { /// One frame for `turn`: bind her if another mind is bound, then one step (a prefill chunk, or /// one token). fn step(&mut self, turn: &mut Turn) -> Result { + if turn.req.response_tx.is_closed() { + return Err(TurnError::CallerReleased); + } + let gap = turn.ready_since.elapsed(); + turn.spent.longest_gap = turn.spent.longest_gap.max(gap); if turn.spent.first_step.is_none() { turn.spent.first_step = Some(turn.submitted.elapsed()); } @@ -603,20 +642,26 @@ impl Driver<'_, '_> { turn.spent.switch += switching.elapsed(); turn.spent.switches += 1; } - if matches!(turn.phase, Phase::Waiting) { + if matches!(turn.phase, Phase::Waiting(_)) { let from = self.resume(turn)?; if from >= turn.prompt.len() { return Err(TurnError::NothingDecoded); } turn.phase = Phase::Prefilling { pos: from }; + if turn.spent.milestones.start() { + let since_admit_ms = record::whole_ms(turn.submitted.elapsed()); + let started = transition::At::FrameStarted { since_admit_ms, reused_tokens: from, prompt_tokens: turn.prompt.len(), switched: turn.spent.switches > 0 }; + self.transition(turn, started); + } } let stepping = Instant::now(); - let (advanced, decoding) = match std::mem::replace(&mut turn.phase, Phase::Waiting) { - Phase::Waiting => (Err(TurnError::NothingDecoded), false), + let (advanced, decoding) = match std::mem::replace(&mut turn.phase, Phase::Waiting(Default::default())) { + Phase::Waiting(_) => (Err(TurnError::NothingDecoded), false), Phase::Prefilling { pos } => (self.prefill_chunk(turn, pos).map(|()| Advanced::Continues), false), Phase::Decoding { token, pos, generated } => (self.decode_token(turn, token, pos, generated), true), }; let stepped = Instant::now(); + turn.ready_since = stepped; let took = stepped.saturating_duration_since(stepping); if decoding { turn.spent.decode += took; @@ -624,9 +669,12 @@ impl Driver<'_, '_> { turn.spent.prefill += took; } self.record.send(record::Fact::Busy { started: stepping, ended: stepped }); - if let Ok(Advanced::Done(TokenEvent::Done { tokens_generated, .. })) = &advanced { + if turn.spent.milestones.step(advanced.is_ok()) { + let progress = transition::At::FirstProgress { since_admit_ms: record::whole_ms(turn.submitted.elapsed()), step_ms: record::whole_ms(took), prefill: !decoding }; + self.transition(turn, progress); + } + if let Ok(Advanced::Done { .. }) = &advanced { self.report_footprint(turn.id, turn.one_off); - self.record.send(record::Fact::Turn(Self::row(turn, *tokens_generated))); } advanced } @@ -637,18 +685,27 @@ impl Driver<'_, '_> { fn resume(&mut self, turn: &mut Turn) -> Result { let basis = turn.basis.clone(); let her = self.engine.active_mut().ok_or(TurnError::NoneActive)?; - turn.spent.shared_prefix_tokens = reuse::common_prefix(&her.parts().tokens.held, &turn.prompt); - let decided = reuse_for(her, &turn.prompt, &basis); - let shared = turn.spent.shared_prefix_tokens; - if matches!(decided, reuse::Reuse::Restart(reuse::Miss::Diverged | reuse::Miss::NoCheckpoint)) - && her.parts().genome == basis && shared > 0 && turn.boundaries[0].is_some_and(|view| shared < view) { - turn.boundaries[1] = Some(shared); + let reuse::Decision { shared, action: decided } = reuse_for(her, &turn.prompt, &basis); + turn.spent.shared_prefix_tokens = shared; + // Prefill will cross this matching prefix again. Take a native checkpoint there + // so the next turn can use it if both token history and recurrent lineage match. + let can_learn = match decided { + reuse::Reuse::Rewind { from } => shared > from, + reuse::Reuse::Restart(reuse::Miss::Diverged | reuse::Miss::NoCheckpoint) => shared > 0, + _ => false, + }; + if can_learn && her.parts().genome == basis && turn.boundaries.view.is_some_and(|view| shared < view) { + turn.boundaries.learned = Some(shared); } let (from, start) = match decided { reuse::Reuse::Append { from } => (from, "append"), reuse::Reuse::Rewind { from } => match self.rewind_to_checkpoint(from) { Ok(()) => (from, "rewind"), - Err(_) => (0, "rewind_refused"), + Err(error) => { + continuum_base::probe!(class = "persona.engine.rewind_failed", persona = %turn.id.0, checkpoint_end = from as u64, + shared_tokens = shared as u64, error = %error, "native rewind failed; turn must prefill"); + (0, "rewind_refused") + } }, reuse::Reuse::Restart(miss) => (0, miss.reason()), }; @@ -663,32 +720,32 @@ impl Driver<'_, '_> { /// Rewind the active mind to her kept checkpoint (taken out and put back, so the engine can read /// it while it moves her). fn rewind_to_checkpoint(&mut self, end: usize) -> Result<(), TurnError> { - let slots = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens.kept; - let index = slots.iter().position(|slot| slot.as_ref().is_some_and(|kept| kept.end == end)).ok_or(TurnError::NoneActive)?; - let kept = slots[index].take(); - let Some(kept) = kept else { return Err(TurnError::NoneActive) }; - let rewound = self.engine.rewind_active(&kept.blocks); - self.record(|her| her.tokens.kept[index] = Some(kept))?; + let snapshot = self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens.take_at(end).ok_or(TurnError::NoneActive)?; + let rewound = self.engine.rewind_active(snapshot.blocks()); + self.record(|her| her.tokens.put_back(snapshot))?; Ok(rewound?) } /// Checkpoint the active mind at her view's end (`end` tokens held), reusing her checkpoint's /// buffers. A refused take keeps none, so a later act restarts instead of rewinding to a stale one. - fn keep_checkpoint(&mut self, turn: &mut Turn, index: usize, end: usize) -> Result<(), TurnError> { + fn keep_checkpoint(&mut self, turn: &mut Turn, kind: Boundary, end: usize) -> Result<(), TurnError> { let taking = Instant::now(); - let previous = self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens.kept[index].take(); - let mut blocks = match previous.map(|kept| kept.blocks).or_else(llama::PersonaCheckpoint::new) { - Some(blocks) => blocks, - None => return Ok(()), // the host could not allocate a checkpoint: she restarts next act, named in its row + let history = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens; + let Some(mut blocks) = history.capture_buffer(kind, end) else { + continuum_base::probe!(class = "persona.engine.checkpoint_allocation_failed", persona = %turn.id.0, + expected_end = end as u64, "native checkpoint buffer allocation failed"); + turn.spent.checkpoint_ms += record::whole_ms(taking.elapsed()); + return Ok(()); }; - let taken = self.engine.checkpoint_active(&mut blocks); - let basis = turn.basis.clone(); - self.record(|her| { - her.tokens.kept[index] = match taken { - Ok(pos) if pos as usize + 1 == end => Some(KeptCheckpoint { blocks, end, basis }), - _ => None, + match self.engine.checkpoint_active(&mut blocks) { + Ok(pos) if pos as usize + 1 == end => { + self.record(|her| her.tokens.save(kind, blocks, end, &turn.basis))?; } - })?; + Ok(pos) => continuum_base::probe!(class = "persona.engine.checkpoint_misaligned", persona = %turn.id.0, + expected_end = end as u64, native_position = i64::from(pos), "discarded misaligned native checkpoint"), + Err(error) => continuum_base::probe!(class = "persona.engine.checkpoint_failed", persona = %turn.id.0, + expected_end = end as u64, error = %error, "native checkpoint capture failed"), + } turn.spent.checkpoint_ms += record::whole_ms(taking.elapsed()); Ok(()) } @@ -697,25 +754,27 @@ impl Driver<'_, '_> { /// token; only it is sampled, since the sampler accepts what it samples (Codex on #6140). fn prefill_chunk(&mut self, turn: &mut Turn, pos: usize) -> Result<(), TurnError> { // A chunk never runs past her view's end, so she can be checkpointed exactly there. - let limit = turn.boundaries.iter().flatten().copied().filter(|boundary| *boundary > pos).min().unwrap_or(turn.prompt.len()); // unwrap_or: no view end ahead, the prompt's end bounds the chunk - let end = (pos + self.batch.get()).min(limit); - let chunk = turn.prompt[pos..end].to_vec(); + let limit = turn.boundaries.next_end(pos, turn.prompt.len()); + // Her turn keeps the Core until it ends (`frame`), so each chunk is as large as the engine's + // batch: nothing is sized to yield to another mind. + let end = pos.saturating_add(self.batch.get()).min(limit); + let chunk = &turn.prompt[pos..end]; let last = end == turn.prompt.len(); let from = i32::try_from(pos).map_err(|_| TurnError::TooLong)?; let len = chunk.len(); - self.engine.submit(Step { tokens: chunk.clone(), from, logits_at_end: last, genes: Arc::clone(&turn.genes) })?; + self.engine.submit(Step { tokens: chunk.to_vec(), from, logits_at_end: last, genes: Arc::clone(&turn.genes) })?; if !last { self.engine.settle()?; - self.record(|her| her.tokens.held.extend_from_slice(&chunk))?; - if let Some(index) = turn.boundaries.iter().position(|boundary| *boundary == Some(end)) { - self.keep_checkpoint(turn, index, end)?; + self.record(|her| her.tokens.held.extend_from_slice(chunk))?; + if let Some(kind) = turn.boundaries.at(end) { + self.keep_checkpoint(turn, kind, end)?; } turn.phase = Phase::Prefilling { pos: end }; return Ok(()); } let at = i32::try_from(len - 1).map_err(|_| TurnError::TooLong)?; let token = self.engine.tier().sample(&mut turn.sampler, at); - self.record(|her| her.tokens.held.extend_from_slice(&chunk))?; + self.record(|her| her.tokens.held.extend_from_slice(chunk))?; self.report_footprint(turn.id, turn.one_off); let pos = i32::try_from(end).map_err(|_| TurnError::TooLong)?; turn.phase = Phase::Decoding { token, pos, generated: 0 }; @@ -726,10 +785,10 @@ impl Driver<'_, '_> { fn decode_token(&mut self, turn: &mut Turn, token: i32, pos: i32, generated: usize) -> Result { let done = |turn: &Turn, generated: usize| { let took = turn.submitted.elapsed(); - Advanced::Done(TokenEvent::Done { + Advanced::Done { tokens_generated: generated, elapsed_ms: took.as_secs().saturating_mul(1000).saturating_add(u64::from(took.subsec_millis())), - }) + } }; // Emit raised her cancel flag: a stop sequence ended her answer, or her caller hung up. What // her blocks computed stays hers. @@ -767,16 +826,18 @@ impl Driver<'_, '_> { fn row(turn: &Turn, generated: usize) -> record::TurnRow { let ms = record::whole_ms; record::TurnRow { + request: turn.req.request.clone(), persona: turn.id.0, one_off: turn.one_off, prompt_tokens: turn.prompt.len() as u64, reused_tokens: turn.spent.reused as u64, shared_prefix_tokens: turn.spent.shared_prefix_tokens as u64, start: turn.spent.start, - boundary: turn.boundaries[0].map(|end| end as u64), - learned_boundary: turn.boundaries[1].map(|end| end as u64), + boundary: turn.boundaries.view.map(|end| end as u64), + learned_boundary: turn.boundaries.learned.map(|end| end as u64), checkpoint_ms: turn.spent.checkpoint_ms, wait_ms: turn.spent.first_step.map(ms), + longest_service_gap_ms: ms(turn.spent.longest_gap), switches: turn.spent.switches, switch_ms: ms(turn.spent.switch), prefill_ms: ms(turn.spent.prefill), @@ -823,10 +884,22 @@ impl Driver<'_, '_> { self.retire_previous() } - /// Park the mind whose retirement finishes. A one-off is dropped, and her blocks with her. + /// Report that `turn` reached `at`; its record stage writes it. + fn transition(&mut self, turn: &Turn, at: transition::At) { + self.record.send(record::Fact::Transition(transition::Transition { request: turn.req.request.clone(), persona: turn.id.0, one_off: turn.one_off, at })); + } + + fn finish_one_off(&mut self, turn: &Turn) { + if turn.one_off { + self.parked.remove(&turn.id); + self.live_one_offs.remove(&turn.id); + } + } + + /// A paused one-off keeps her blocks until she finishes, just like a paused resident. fn retire_previous(&mut self) -> Result<(), TurnError> { let Some(previous) = self.engine.finish_retirement()? else { return Ok(()) }; - if resident(&previous) { + if resident(&previous) || self.live_one_offs.contains(&previous.id()) { self.parked.insert(previous.id(), previous); } Ok(()) diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs new file mode 100644 index 0000000000..4a8bfc6427 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs @@ -0,0 +1,139 @@ +//! How an admitted turn leaves the engine. One owner (`Driver::end`) ends every admitted turn, so +//! each ends in exactly one terminal record: its turn row when answered, else +//! `persona.engine.refused` with why (Codex on ce8a894e93: a stop and a closed submission channel +//! ended turns with no record). A stop is acknowledged only once those records are processed. + +use continuum_base::probe_writes::Reading; +use continuum_flow::Outbox; +use tokio::sync::oneshot; + +use super::super::Records; +use super::{emit, record, report, transition, Driver, Suspended, TokenEvent, Turn, TurnError}; + +/// A stop's suspend, awaiting its acknowledgement. +pub(super) struct Stop { + pub(super) reply: tokio::sync::oneshot::Sender, + pub(super) suspension: Suspension, +} + +/// What a stop's suspend did natively: minds preserved, and every mind it could not preserve, with +/// why. Its acknowledgement adds whether the records of the turns it ended were written. +pub(super) struct Suspension { + pub(super) preserved: usize, + pub(super) retained: Vec<(uuid::Uuid, String)>, +} + +/// How an admitted turn left the engine. +pub(super) enum Ending { + /// She answered: EOG, a stop sequence, or max_tokens. + Answered { tokens_generated: usize, elapsed_ms: u64 }, + /// A step was refused or failed, or her caller hung up. + Refused(TurnError), + /// The engine is stopping: what her blocks computed stays hers. + Stopping, + /// Every submission handle was dropped while her turn was still admitted. + Closed, +} + +impl Ending { + /// Why an unanswered turn ended, as its caller and its record read it. + fn reason(&self) -> String { + match self { + Self::Answered { .. } => "answered".into(), + Self::Refused(refused) => refused.to_string(), + Self::Stopping => "the engine is stopping: her state is preserved".into(), + Self::Closed => "every submission handle was dropped".into(), + } + } +} + +impl Driver<'_, '_> { + /// End `turn`: the one place an admitted turn leaves the engine, so each ends in exactly one + /// terminal record (its turn row when answered, else `persona.engine.refused`), its one-off + /// mind released, and its caller told. + pub(super) fn end(&mut self, turn: Turn, ending: Ending) { + let event = match ending { + Ending::Answered { tokens_generated, elapsed_ms } => { + self.record.send(record::Fact::Turn(Self::row(&turn, tokens_generated))); + TokenEvent::Done { tokens_generated, elapsed_ms } + } + unanswered => { + let reason = unanswered.reason(); + self.transition(&turn, transition::At::Refused { since_admit_ms: record::whole_ms(turn.submitted.elapsed()), reason: reason.clone() }); + TokenEvent::Error(reason) + } + }; + self.finish_one_off(&turn); + self.emit.send(emit::Out::End { answer: turn.answer, event }); + } + + /// Acknowledge a stop: its native suspend result as it is, with what the records of the turns it + /// ended can be said to be. + pub(super) fn acknowledge(&mut self, stop: Stop, stages_on: &tokio::runtime::Handle) { + let records = self.settle_records(stages_on); + let Suspension { preserved, retained } = stop.suspension; + report(stop.reply, Suspended { records, preserved, retained }); + } + + /// Settle what a stop must not lose before it is acknowledged, or the loop ends ([`settle`]). + pub(super) fn settle_records(&mut self, stages_on: &tokio::runtime::Handle) -> Records { + stages_on.block_on(settle(&mut self.emit, &mut self.record, record::Fact::Barrier, &mut self.log_failures)) + } + + /// Every submission handle was dropped: every admitted turn ends, its records are settled, and + /// what Emit still holds (answer ends included) passes to a drain owner on the stage runtime, so + /// a caller still reading gets her answer's end in order and this thread ends without waiting on + /// Emit (Codex on #6208 at 162fbe5fa7: a full Emit dropped them with the driver). + pub(super) fn close(mut self, turns: &mut Vec, stages_on: &tokio::runtime::Handle) { + for turn in turns.drain(..) { + self.end(turn, Ending::Closed); + } + self.settle_records(stages_on); + hand_off(self.emit, stages_on); + } +} + +/// Give `emit` to a task that hands over everything it holds, in order, then drops it, which ends +/// its stage once that stage has handled the rest. +pub(super) fn hand_off(mut emit: Outbox, on: &tokio::runtime::Handle) -> tokio::task::JoinHandle<()> { + on.spawn(async move { emit.drain().await }) +} + +/// The driver thread's last act: wait for both stages to end, never closing their intake. A stage +/// ends once its last producer is gone and it has handled what it took, so what a closing driver +/// handed to its drain owner still reaches its callers (Codex on 8f386fb4e1: stopping Emit's intake +/// here raced that drain and dropped the ends it had not yet pushed). Every producer is the +/// driver's or the drain owner's, and both end, so this always returns. +pub(in super::super) async fn finish( + emit: continuum_flow::StageWorker, + record: continuum_flow::StageWorker, +) -> (Result<(), tokio::task::JoinError>, Result<(), tokio::task::JoinError>) { + tokio::join!(emit.join(), record.join()) +} + +/// Every record sent so far is processed, confirmed by the record stage answering a barrier it reaches +/// after them (it is FIFO), with the probe-log writes that failed since `seen`. Emit is flushed but +/// never awaited: a caller that stopped reading her answer never holds the stop (Codex on 8e597e1bcd). +/// A record stage that ended first reads `Unconfirmed`. +pub(super) async fn settle( + emit: &mut Outbox, + record: &mut Outbox, + barrier: impl FnOnce(oneshot::Sender<()>) -> R, + seen: &mut Reading, +) -> Records { + emit.flush(); + let (processed, answered) = oneshot::channel(); + record.send(barrier(processed)); + record.drain().await; + if answered.await.is_ok() { + let now = Reading::now(); + Records::Processed { write_failures: now.since(std::mem::replace(seen, now)) } + } else { + continuum_base::probe!(class = "persona.engine.records_unconfirmed", "the record stage ended before confirming a stop's last records"); + Records::Unconfirmed + } +} + +#[cfg(test)] +#[path = "ending_tests.rs"] +mod tests; diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending_tests.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending_tests.rs new file mode 100644 index 0000000000..0ecbf1abf7 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending_tests.rs @@ -0,0 +1,150 @@ +use super::*; +use continuum_flow::{spawn_stage, Capacity, Qos, Stage}; +use std::num::NonZeroUsize; + +/// What the test stages take: an item, or a record stage's barrier. +enum Fact { + Item, + /// An answer's output, numbered in the order it was sent. + Numbered(u32), + Barrier(oneshot::Sender<()>), +} + +/// A record stage: answers each barrier once everything before it is handled. +struct Answers; + +impl Stage for Answers { + type Input = Fact; + const QOS: Qos = Qos::Utility; + async fn handle(&mut self, fact: Fact) { + if let Fact::Barrier(written) = fact { + assert!(written.send(()).is_ok(), "the settle awaits its barrier"); + } + } +} + +/// An Emit sink whose caller stopped reading: it never finishes handling what it took. +struct Stalls; + +impl Stage for Stalls { + type Input = Fact; + const QOS: Qos = Qos::Utility; + async fn handle(&mut self, _fact: Fact) { + std::future::pending::<()>().await; + } +} + +fn one() -> Capacity { + Capacity::granted(NonZeroUsize::MIN) +} + +// what this catches: a stop acknowledged as settled when the record stage ended before +// confirming its last records (Codex on 8e597e1bcd), and a healthy stop misread as unconfirmed. +#[tokio::test] +async fn records_read_processed_only_when_the_record_stage_confirms_them() { + let (emit_input, _emit) = spawn_stage(Answers, one()); + let mut emit = Outbox::new(emit_input); + + let (record_input, _record) = spawn_stage(Answers, one()); + let mut record = Outbox::new(record_input); + record.send(Fact::Item); + assert!(matches!(settle(&mut emit, &mut record, Fact::Barrier, &mut Reading::now()).await, Records::Processed { .. })); + + let (stopped_input, stopped) = spawn_stage(Answers, one()); + stopped.stop(); + let mut stopped_record = Outbox::new(stopped_input); + assert_eq!(settle(&mut emit, &mut stopped_record, Fact::Barrier, &mut Reading::now()).await, Records::Unconfirmed, "a record stage that ended cannot confirm"); +} + +// what this catches: a stop held by a caller that stopped reading her answer (Codex on 8e597e1bcd: +// the settle joined Emit's drain), with output still queued behind the stalled sink. +#[tokio::test] +async fn a_stalled_emit_sink_never_holds_the_stop() { + let (emit_input, _emit) = spawn_stage(Stalls, one()); + let mut emit = Outbox::new(emit_input); + for _ in 0..4 { + emit.send(Fact::Item); + } + assert!(emit.waiting() > 0, "output is queued behind the stalled sink"); + + let (record_input, _record) = spawn_stage(Answers, one()); + let mut record = Outbox::new(record_input); + assert!(matches!(settle(&mut emit, &mut record, Fact::Barrier, &mut Reading::now()).await, Records::Processed { .. })); + assert!(emit.waiting() > 0, "the stalled sink's output is left for its caller, not awaited"); +} + +// what this catches (Codex on #6208 at 162fbe5fa7): a settle that reads its records written while the +// probe log failed to write them, and a failure counted again at the next settle. +#[tokio::test] +async fn a_settle_reports_the_log_writes_that_failed_in_its_window() { + let (emit_input, _emit) = spawn_stage(Answers, one()); + let mut emit = Outbox::new(emit_input); + let (record_input, _record) = spawn_stage(Answers, one()); + let mut record = Outbox::new(record_input); + let mut seen = Reading::now(); + + continuum_base::probe_writes::count_failure(); + let failed = settle(&mut emit, &mut record, Fact::Barrier, &mut seen).await; + assert!(matches!(failed, Records::Processed { write_failures } if write_failures >= 1), "{failed:?}"); + assert_eq!(seen, Reading::now(), "the window moves to this settle, so the failure is not reported twice"); +} + +/// An Emit stage that hands each numbered output to its caller. +struct Delivers(tokio::sync::mpsc::UnboundedSender); + +impl Stage for Delivers { + type Input = Fact; + const QOS: Qos = Qos::Utility; + async fn handle(&mut self, fact: Fact) { + if let Fact::Numbered(n) = fact { + assert!(self.0.send(n).is_ok(), "the test reads every output"); + } + } +} + +// what this catches (Codex on #6208 at 162fbe5fa7): every submission handle dropped while Emit was +// full, and the answer ends still queued for it dropped with the driver, so a caller still reading +// never heard her turn end. +#[tokio::test] +async fn a_closed_engine_hands_a_full_emit_to_a_drain_owner_in_order() { + let (delivered, mut caller) = tokio::sync::mpsc::unbounded_channel(); + let (emit_input, _emit) = spawn_stage(Delivers(delivered), one()); + let mut emit = Outbox::new(emit_input); + for n in 0..8 { + emit.send(Fact::Numbered(n)); + } + assert!(emit.waiting() > 0, "Emit is full: outputs wait behind it"); + + assert!(hand_off(emit, &tokio::runtime::Handle::current()).await.is_ok(), "the drain owner finishes"); + let mut heard = Vec::new(); + while heard.len() < 8 { + let Some(output) = caller.recv().await else { break }; // a lost output ends the stream short, and fails below + heard.push(output); + } + assert_eq!(heard, (0..8).collect::>(), "in the order they were sent"); +} + +// what this catches (Codex on 8f386fb4e1): the driver thread closing Emit's intake right after a +// closing driver handed its full outbox to the drain owner, so ends the drain had not yet pushed +// came back refused and were dropped. Shutdown here is the thread's own: hand off, then `finish`. +#[tokio::test] +async fn shutdown_with_a_full_emit_delivers_every_end_before_the_stages_finish() { + let (delivered, mut caller) = tokio::sync::mpsc::unbounded_channel(); + let (emit_input, emit_worker) = spawn_stage(Delivers(delivered), one()); + let (record_input, record_worker) = spawn_stage(Answers, one()); + let mut emit = Outbox::new(emit_input); + for n in 0..8 { + emit.send(Fact::Numbered(n)); + } + assert!(emit.waiting() > 0, "Emit is full: ends wait behind it"); + drop(record_input); // the closed driver's record outbox, already settled + + let _drain = hand_off(emit, &tokio::runtime::Handle::current()); + let (emit_ended, record_ended) = finish(emit_worker, record_worker).await; + assert!(emit_ended.is_ok() && record_ended.is_ok(), "both stages end on their own"); + let mut heard = Vec::new(); + while let Ok(output) = caller.try_recv() { + heard.push(output); + } + assert_eq!(heard, (0..8).collect::>(), "every end reached its caller, in order, before the stages finished"); +} diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs new file mode 100644 index 0000000000..a717d295fd --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs @@ -0,0 +1,175 @@ +use super::{reuse, Basis, Footprint, Held}; + +/// The tokens her blocks hold, and her checkpoint at her last view's end while what she holds still +/// runs through it. +#[derive(Default)] +pub(super) struct History { + pub(super) held: Vec, + /// View end, latest learned prefix, and earliest still-valid learned prefix. + kept: [Option; 3], +} + +/// Her checkpoint and what makes it valid: she held exactly `held[..end]` under `basis` when it was +/// taken, and nothing she holds below `end` has changed since (a cut below it drops it). +struct KeptCheckpoint { + blocks: llama::PersonaCheckpoint, + end: usize, + basis: Basis, +} + +/// Her checkpoint holds her recurrent rows in host memory. +impl Footprint for KeptCheckpoint { + fn held(&self) -> Held { + Held::host(self.blocks.bytes() as u64) + } +} + +/// Her token history and her checkpoint. Her blocks in the context are reported by the tier that +/// binds them; [`Bound`] is that child's view. +impl Footprint for History { + fn held(&self) -> Held { + self.kept + .iter() + .fold(self.held.held(), |bytes, kept| bytes + kept.held()) + } +} + +impl History { + /// Keep only her first `len` tokens; a cut below her checkpoint's end drops the checkpoint. + pub(super) fn cut(&mut self, len: usize) { + self.held.truncate(len); + for slot in &mut self.kept { + if slot.as_ref().is_some_and(|kept| kept.end > len) { + *slot = None; + } + } + } + + /// Where `prompt` under `basis` would start for her, whose blocks were computed under `under` + /// (`reuse::choose`), deciding nothing and moving nothing: the bind uses it to resume her, the + /// frame to size her turn's prefill. + pub(super) fn reuse(&self, under: &Basis, prompt: &[i32], basis: &Basis) -> reuse::Decision { + let kept = self.kept.iter().flatten().map(|kept| reuse::Kept { + end: kept.end, + basis: &kept.basis, + }); + reuse::choose( + reuse::History { + basis: under, + tokens: &self.held, + }, + kept, + reuse::History { + basis, + tokens: prompt, + }, + ) + } +} + +#[derive(Clone, Copy)] +pub(super) enum Boundary { + View, + Learned, +} + +pub(super) struct Boundaries { + pub(super) view: Option, + pub(super) learned: Option, +} +impl Boundaries { + fn entries(&self) -> impl Iterator { + [ + (Boundary::View, self.view), + (Boundary::Learned, self.learned), + ] + .into_iter() + .filter_map(|(kind, end)| Some((kind, end?))) + } + pub(super) fn next_end(&self, pos: usize, prompt_end: usize) -> usize { + self.entries() + .map(|(_, end)| end) + .filter(|end| *end > pos) + .min() + .unwrap_or(prompt_end) // unwrap_or: the prompt ends the final frame + } + pub(super) fn at(&self, end: usize) -> Option { + self.entries() + .find_map(|(kind, pos)| (pos == end).then_some(kind)) + } +} +impl From> for History { + fn from(held: Vec) -> Self { + Self { + held, + ..Self::default() + } + } +} + +impl History { + pub(super) fn deepest(&self) -> Option { + self.kept.iter().flatten().map(|s| s.end).max() + } + pub(super) fn take_at(&mut self, end: usize) -> Option { + let (slot, entry) = self + .kept + .iter_mut() + .enumerate() + .find(|(_, entry)| entry.as_ref().is_some_and(|s| s.end == end))?; + Some(Snapshot { + slot, + checkpoint: entry.take()?, + }) + } + pub(super) fn put_back(&mut self, snapshot: Snapshot) { + self.kept[snapshot.slot] = Some(snapshot.checkpoint); + } + fn slot(&mut self, kind: Boundary) -> &mut Option { + let [view, learned, _] = &mut self.kept; + match kind { + Boundary::View => view, + Boundary::Learned => learned, + } + } + pub(super) fn capture_buffer( + &mut self, + kind: Boundary, + end: usize, + ) -> Option { + if let Boundary::Learned = kind { + let [_, latest, earliest] = &mut self.kept; + if latest.as_ref().is_some_and(|prior| { + prior.end < end && earliest.as_ref().is_none_or(|s| prior.end < s.end) + }) { + std::mem::swap(latest, earliest); + } + } + self.slot(kind) + .take() + .map(|s| s.blocks) + .or_else(llama::PersonaCheckpoint::new) + } + pub(super) fn save( + &mut self, + kind: Boundary, + blocks: llama::PersonaCheckpoint, + end: usize, + basis: &Basis, + ) { + *self.slot(kind) = Some(KeptCheckpoint { + blocks, + end, + basis: basis.clone(), + }); + } +} +pub(super) struct Snapshot { + slot: usize, + checkpoint: KeptCheckpoint, +} +impl Snapshot { + pub(super) fn blocks(&self) -> &llama::PersonaCheckpoint { + &self.checkpoint.blocks + } +} diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs index 322b68e98e..9378cbecf8 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs @@ -1,77 +1,105 @@ -//! Which turn the next frame advances (CONTINUUM-ENGINE 4.13/4.15). A frame is one step: one prefill -//! chunk or one decoded token, never a whole turn, so a mind with a long cold prompt never holds the -//! engine while a mind with a short tail waits behind her (the M5, 2026-11-18, build 88074d9300: -//! turns served whole, back to back, waited 300-360 s behind one another's prefills). +//! Which turn the Core advances next (CONTINUUM-ENGINE 4.13/4.15): one mind at a time, and a turn +//! in progress runs to its end. Joel, 2026-11-21: "you don't cut it up, run single lane; context +//! switching is faster." //! -//! The rule, in order: -//! 1. the active mind's turn that is decoding continues: one mind decodes until she stops, and a -//! switch mid-answer would only add a switch; -//! 2. otherwise the turn with the least prefill left goes first, its remaining tokens discounted by -//! how long it has waited, so a short tail never waits behind a long prompt and a long prompt -//! still ages to the front; -//! 3. ties go to the active mind (no switch). +//! The policy this replaces gave every ready turn a slice of a one-second service budget, so a turn +//! was cut into frames shared with every other ready mind. On the M5 (build 56913f640b, 2026-11-21 +//! 04:14-04:29 UTC) that meant 20 to 520 switches per turn at 12 to 25 ms each, up to 8.5 s of +//! switching inside one turn, for no gain to the turn being cut. Its reason was cold prompts (the +//! M5, 2026-11-18: whole turns back to back, short tails waiting 300-360 s behind cold prefills); +//! the same 2026-11-21 read showed most turns reusing 71 to 98% of their prompt. Whether a cold +//! prompt still needs its own handling is measured, not assumed. //! -//! The policy is this one pure function, so the owner of goal 9's scheduler replaces it here and -//! nowhere else. +//! So: the bound mind's turn, once started, keeps the Core until it ends. When no turn is in +//! progress, turns waiting at least half a second go oldest first. Below that threshold, +//! remaining prefill cost and age decide. Affinity breaks ties. -/// A turn as the frame sees it. +/// A turn as the pick sees it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct Candidate { /// Her mind is the one bound to the decoding stream now. pub active: bool, - /// Her prompt is prefilled and she is producing tokens. - pub decoding: bool, + /// Her turn has begun: prefilling or decoding. + pub started: bool, /// Prompt tokens still to prefill (0 once decoding). pub remaining: usize, - /// Milliseconds since her turn was submitted. + /// Milliseconds since admission or her most recent completed frame. pub waited_ms: u64, } impl Candidate { - /// Remaining work discounted by age: tokens per second waited, plus one so a fresh turn is its - /// own size. Ballpark by design; only the order matters. - fn cost(&self) -> u128 { - (self.remaining as u128 * 1_000) / (1_000 + u128::from(self.waited_ms)) + fn before(&self, other: &Self) -> std::cmp::Ordering { + // derived-or-floor: a half-second queue wait meets the interactive stall threshold. + // At the next free boundary, age takes precedence over estimated prefill cost. + const WAIT_BUDGET_MS: u64 = 500; + if self.waited_ms.max(other.waited_ms) >= WAIT_BUDGET_MS { + return other.waited_ms.cmp(&self.waited_ms) + .then(self.remaining.cmp(&other.remaining)) + .then(other.active.cmp(&self.active)); + } + let discounted = |turn: &Self, by: &Self| turn.remaining as u128 * (1_000 + u128::from(by.waited_ms)); + discounted(self, other) + .cmp(&discounted(other, self)) + .then(other.waited_ms.cmp(&self.waited_ms)) + .then(other.active.cmp(&self.active)) } } -/// The index of the turn the next frame advances, or `None` for no turns. +/// The index of the turn the Core advances next, or `None` for no turns. pub(super) fn pick(turns: &[Candidate]) -> Option { - if let Some(decoding) = turns.iter().position(|turn| turn.active && turn.decoding) { - return Some(decoding); + if let Some(running) = turns.iter().position(|turn| turn.active && turn.started) { + return Some(running); } - turns - .iter() - .enumerate() - .min_by_key(|(_, turn)| (turn.cost(), !turn.active)) - .map(|(index, _)| index) + turns.iter().enumerate().min_by(|(_, a), (_, b)| a.before(b)).map(|(index, _)| index) } #[cfg(test)] mod tests { use super::*; - fn turn(active: bool, decoding: bool, remaining: usize, waited_ms: u64) -> Candidate { - Candidate { active, decoding, remaining, waited_ms } + fn turn(active: bool, started: bool, remaining: usize, waited_ms: u64) -> Candidate { + Candidate { active, started, remaining, waited_ms } } - // what this catches: a mind's cold prompt holding the engine while a short tail waits (the M5, - // 2026-11-18: whole turns back to back, 300-360 s waits). The short tail goes first; the active - // mind's answer in progress is never cut for a switch; a long prompt still reaches the front by - // waiting; equal costs keep the mind already bound. #[test] - fn a_short_tail_never_waits_behind_a_long_prompt_and_an_answer_is_never_cut() { - assert_eq!(pick(&[]), None); - let long_active = turn(true, false, 60_000, 0); - let short = turn(false, false, 300, 0); - assert_eq!(pick(&[long_active, short]), Some(1), "the short tail switches in at the chunk boundary"); + fn a_cold_turn_gets_the_next_boundary_after_its_wait_budget() { + let warm = turn(true, false, 0, 0); + assert_eq!(pick(&[warm, turn(false, false, 60_000, 499)]), Some(0)); + let overdue = turn(false, false, 60_000, 500); + assert_eq!(pick(&[warm, overdue]), Some(1)); + assert_eq!(pick(&[turn(true, false, 1, 501), overdue]), Some(0)); + } + // what this catches: a turn in progress cut up to serve other minds (the 2026-11-21 read: 20 to + // 520 switches per turn), a turn waiting forever behind fresh short ones, and a needless switch + // on a tie. + #[test] + fn a_turn_in_progress_runs_to_its_end_and_a_long_wait_still_comes_forward() { + assert_eq!(pick(&[]), None); + let prefilling = turn(true, true, 60_000, 0); + assert_eq!(pick(&[turn(false, false, 300, 90_000), prefilling]), Some(1), "an overdue turn waits for the running one to end"); let answering = turn(true, true, 0, 0); - assert_eq!(pick(&[turn(false, false, 1, 90_000), answering]), Some(1), "her answer finishes first"); - + assert_eq!(pick(&[turn(false, false, 1, 90_000), answering]), Some(1), "an answer in progress is never cut"); let aged = turn(false, false, 60_000, 600_000); assert_eq!(pick(&[turn(false, false, 1_000, 0), aged]), Some(1), "ten minutes of waiting brings a long prompt forward"); - assert_eq!(pick(&[turn(false, false, 500, 0), turn(true, false, 500, 0)]), Some(1), "a tie keeps the bound mind"); } + + // what this catches (Codex on #6208 at 162fbe5fa7): an aged and a fresh one-token tail rounding to + // the same cost, affinity winning every such tie, and the bound mind's repeated arrivals starving + // an older mind. + #[test] + fn a_bound_mind_that_keeps_arriving_never_starves_an_older_one() { + assert_eq!(pick(&[turn(true, false, 1, 5), turn(false, false, 1, 90_000)]), Some(1), "the aged one-token tail goes first"); + assert_eq!(pick(&[turn(true, false, 0, 0), turn(false, false, 0, 1)]), Some(1), "equal cost goes to the longer wait"); + + // The bound mind answers and arrives again, fully cached, round after round; the older mind, + // also fully cached, waits. It is served on the first round it is ready, not never. + let mut older = turn(false, false, 0, 0); + let served = (1..=5u64).find(|round| { + older.waited_ms = round * 2_000; + pick(&[turn(true, false, 0, 0), older]) == Some(1) + }); + assert_eq!(served, Some(1), "the older mind is served on its first round"); + } } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs index a2a51b51b6..c2c0128f3a 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs @@ -40,13 +40,20 @@ pub(super) fn whole_ms(span: Duration) -> u64 { pub(super) enum Fact { /// The engine worked from `started` to `ended`. Busy { started: Instant, ended: Instant }, - /// A turn ended. + /// A turn reached a transition (admitted, frame started, first progress, refused). + Transition(super::transition::Transition), + /// A turn ended with an answer. Turn(TurnRow), + /// Answered once every fact sent before it has been written: the stage is FIFO, so a stop + /// acknowledges only after its last turns' records are written. + Barrier(tokio::sync::oneshot::Sender<()>), } /// One finished turn: where her seconds went. Built by the engine from its own counters (no work), /// written here. pub(super) struct TurnRow { + /// The submitted request this turn served, so its completion joins its transitions by identity. + pub request: Option, pub persona: uuid::Uuid, pub one_off: bool, pub prompt_tokens: u64, @@ -57,6 +64,7 @@ pub(super) struct TurnRow { pub learned_boundary: Option, pub checkpoint_ms: u64, pub wait_ms: Option, + pub longest_service_gap_ms: u64, pub switches: u64, pub switch_ms: u64, pub prefill_ms: u64, @@ -73,6 +81,7 @@ impl TurnRow { fn write(self) { continuum_base::probe!( class = "persona.engine.turn", + request = ?self.request.as_ref().map(super::RequestId::as_str), persona = %self.persona, one_off = self.one_off, prompt_tokens = self.prompt_tokens, @@ -83,6 +92,7 @@ impl TurnRow { learned_boundary = ?self.learned_boundary, checkpoint_ms = self.checkpoint_ms, wait_ms = ?self.wait_ms, + longest_service_gap_ms = self.longest_service_gap_ms, switches = self.switches, switch_ms = self.switch_ms, prefill_ms = self.prefill_ms, @@ -159,10 +169,16 @@ impl Stage for Record { } // A window is one turn: from the last turn's end through this one's last step, so the // idle gap before her turn counts against the share as much as the work in it. + Fact::Transition(transition) => transition.write(self.incarnation), Fact::Turn(row) => { row.write(); self.close_window(self.last_end); } + Fact::Barrier(written) => { + if written.send(()).is_err() { + continuum_base::probe!(class = "persona.engine.barrier_unheard", "a stop stopped waiting for its records to be written"); + } + } } } } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs index e5eac7267a..b6be1f523d 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs @@ -54,9 +54,7 @@ impl Miss { } /// The tokens two sequences share from their start. -pub(super) fn common_prefix(a: &[i32], b: &[i32]) -> usize { - a.iter().zip(b).take_while(|(x, y)| x == y).count() -} +pub(super) use continuum_persona_engine::turn::common_prefix; /// One of her checkpoints as reuse sees it: the tokens it holds through (exclusive end) and its basis. #[derive(Clone, Copy)] @@ -69,28 +67,33 @@ pub(super) struct Kept<'a, B> { /// the furthest one both histories hold unchanged under the same genes. Her head's checkpoint /// serves a turnover, which changes her view but not her head (the M5, 2026-11-19, 48a1dc80cd: 17 /// of 30 turns re-prefilled from 0 behind an unchanged head, ~180k of 422,847 tokens). -pub(super) fn choose<'a, B: PartialEq + 'a>(held: History<'_, B>, kept: impl IntoIterator>, next: History<'_, B>) -> Reuse { - let (held_tokens, prompt, basis) = (held.tokens, next.tokens, next.basis); - // The prompt extends her whole held history (her own generated tokens included): append. - if let continuum_persona_engine::turn::Prefill::Append { from } = continuum_persona_engine::turn::plan(held, next) { - return Reuse::Append { from }; +pub(super) struct Decision { + pub shared: usize, + pub action: Reuse, +} + +pub(super) fn choose<'a, B: PartialEq + 'a>(held: History<'_, B>, kept: impl IntoIterator>, next: History<'_, B>) -> Decision { + let comparison = held.compare(&next); + let shared = comparison.shared; + let decide = |action| Decision { shared, action }; + let (held, prompt, basis) = (held.tokens, next.tokens, next.basis); + if let continuum_persona_engine::turn::Prefill::Append { from } = comparison.prefill { + return decide(Reuse::Append { from }); } - let held = held_tokens; let mut kept = kept.into_iter().peekable(); if kept.peek().is_none() { - return Reuse::Restart(if held.is_empty() { Miss::Cold } else { Miss::NoCheckpoint }); + return decide(Reuse::Restart(if held.is_empty() { Miss::Cold } else { Miss::NoCheckpoint })); } let mut same_genes = kept.filter(|kept| kept.basis == basis).peekable(); if same_genes.peek().is_none() { - return Reuse::Restart(Miss::Basis); + return decide(Reuse::Restart(Miss::Basis)); } // A checkpoint's end must be held unchanged by both, and leave a token to sample from. - let shared = common_prefix(held, prompt); - same_genes + decide(same_genes .map(|kept| kept.end) .filter(|end| *end > 0 && *end < prompt.len() && *end <= shared) .max() - .map_or(Reuse::Restart(Miss::Diverged), |from| Reuse::Rewind { from }) + .map_or(Reuse::Restart(Miss::Diverged), |from| Reuse::Rewind { from })) } #[cfg(test)] @@ -113,20 +116,20 @@ mod tests { let mut next: Vec = (0..80).collect(); next.extend([900, 901, 902]); // a new trailer and her call, rendered differently let kept = [Kept { end: 80, basis: &genes }]; - assert_eq!(choose(h(&held, &genes), kept, h(&next, &genes)), Reuse::Rewind { from: 80 }); + assert_eq!(choose(h(&held, &genes), kept, h(&next, &genes)).action, Reuse::Rewind { from: 80 }); let mut early: Vec = (0..40).collect(); early.push(777); // her view itself changed (a new epoch): before her checkpoint early.extend(41..90); - assert_eq!(choose(h(&held, &genes), kept, h(&early, &genes)), Reuse::Restart(Miss::Diverged)); + assert_eq!(choose(h(&held, &genes), kept, h(&early, &genes)).action, Reuse::Restart(Miss::Diverged)); - assert_eq!(choose(h(&held, &genes), kept, h(&next, &"tuned")), Reuse::Restart(Miss::Basis)); - assert_eq!(choose(h(&held, &genes), [], h(&next, &genes)), Reuse::Restart(Miss::NoCheckpoint)); - assert_eq!(choose(h(&[], &genes), [], h(&next, &genes)), Reuse::Restart(Miss::Cold)); + assert_eq!(choose(h(&held, &genes), kept, h(&next, &"tuned")).action, Reuse::Restart(Miss::Basis)); + assert_eq!(choose(h(&held, &genes), [], h(&next, &genes)).action, Reuse::Restart(Miss::NoCheckpoint)); + assert_eq!(choose(h(&[], &genes), [], h(&next, &genes)).action, Reuse::Restart(Miss::Cold)); let mut extends = held.clone(); extends.extend([5, 6]); - assert_eq!(choose(h(&held, &genes), kept, h(&extends, &genes)), Reuse::Append { from: 100 }); + assert_eq!(choose(h(&held, &genes), kept, h(&extends, &genes)).action, Reuse::Append { from: 100 }); } // what this catches (the M5, 2026-11-19, 48a1dc80cd: 17 of 30 turns re-prefilled from 0 behind @@ -140,17 +143,17 @@ mod tests { let kept = [Kept { end: 80, basis: &genes }, Kept { end: 20, basis: &genes }]; let mut turned: Vec = (0..20).collect(); turned.extend(500..560); // a new epoch: her view re-rendered behind the same head - assert_eq!(choose(h(&held, &genes), kept, h(&turned, &genes)), Reuse::Rewind { from: 20 }); + assert_eq!(choose(h(&held, &genes), kept, h(&turned, &genes)).action, Reuse::Rewind { from: 20 }); let mut trailer: Vec = (0..80).collect(); trailer.push(900); - assert_eq!(choose(h(&held, &genes), kept, h(&trailer, &genes)), Reuse::Rewind { from: 80 }); + assert_eq!(choose(h(&held, &genes), kept, h(&trailer, &genes)).action, Reuse::Rewind { from: 80 }); let mut head_changed: Vec = vec![777]; head_changed.extend(1..90); - assert_eq!(choose(h(&held, &genes), kept, h(&head_changed, &genes)), Reuse::Restart(Miss::Diverged)); + assert_eq!(choose(h(&held, &genes), kept, h(&head_changed, &genes)).action, Reuse::Restart(Miss::Diverged)); let mixed = [Kept { end: 80, basis: &"tuned" }, Kept { end: 20, basis: &genes }]; - assert_eq!(choose(h(&held, &genes), mixed, h(&trailer, &genes)), Reuse::Rewind { from: 20 }, "only her checkpoints under these genes count"); + assert_eq!(choose(h(&held, &genes), mixed, h(&trailer, &genes)).action, Reuse::Rewind { from: 20 }, "only her checkpoints under these genes count"); } } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs new file mode 100644 index 0000000000..f33fa16f40 --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs @@ -0,0 +1,171 @@ +//! A turn's transitions inside the engine, each recorded once: admitted to the driver's queue, its +//! first frame started, and its first successful native progress. Keyed by the submitted request's +//! id and the engine's incarnation, so a stall reads as the last transition it reached, on which +//! engine (the M5, 2026-11-21: Aris entered `generate_text` at 00:48:32 and dropped 1,499 s later +//! with no record of whether the engine ever held her turn). + +use super::RequestId; + +/// Where a turn has reached. +pub(super) enum At { + /// The driver took her turn into its queue. + Admitted { + /// Turns in the queue, hers included. + queue_depth: usize, + prompt_tokens: usize, + /// Since her turn was handed to the scheduler. + since_submit_ms: u64, + }, + /// Her first frame began: she is bound, and her prefill's start is known. It may still block or + /// fail; [`At::FirstProgress`] is the proof it advanced. + FrameStarted { + /// Since the driver admitted her turn. + since_admit_ms: u64, + /// Prompt tokens her blocks already held. + reused_tokens: usize, + prompt_tokens: usize, + /// Whether reaching her took a switch from another mind. + switched: bool, + }, + /// Her turn was refused at the door: its prompt leaves no room in one stream. It was never + /// admitted, so it has no other transition. + Infeasible { prompt_tokens: usize, capacity: usize }, + /// Her turn ended without an answer: refused, failed, or her caller hung up. Every admitted turn + /// ends in exactly one of this or `persona.engine.turn`. + Refused { + /// Since the driver admitted her turn. + since_admit_ms: u64, + /// Why, as the driver's typed error states it. + reason: String, + }, + /// Her first step that succeeded natively: a prefill chunk landed, or a token decoded. + FirstProgress { + /// Since the driver admitted her turn. + since_admit_ms: u64, + /// How long that step took. + step_ms: u64, + /// Whether that step was a prefill chunk (otherwise a decoded token). + prefill: bool, + }, +} + +/// How far a turn's once-only transitions have been reported: progress implies a start. +#[derive(Default, Clone, Copy, PartialEq, Eq)] +pub(super) enum Milestones { + #[default] + Admitted, + Started, + Progressed, +} + +impl Milestones { + /// Her first frame begins: true the first time only. + pub(super) fn start(&mut self) -> bool { + let first = *self == Self::Admitted; + if first { + *self = Self::Started; + } + first + } + + /// A step ended, `succeeded` or not: true only for the first that succeeded. + pub(super) fn step(&mut self, succeeded: bool) -> bool { + let first = succeeded && *self != Self::Progressed; + if first { + *self = Self::Progressed; + } + first + } +} + +/// One transition of one turn. +pub(super) struct Transition { + pub request: Option, + pub persona: uuid::Uuid, + pub one_off: bool, + pub at: At, +} + +impl Transition { + /// Write it, tagged with the incarnation of the engine that served it. + pub(super) fn write(self, incarnation: u64) { + // The same shape the adapter logs (`Some("…")`), so the two ends join exactly. + let request = self.request.as_ref().map(RequestId::as_str); + match self.at { + At::Admitted { queue_depth, prompt_tokens, since_submit_ms } => continuum_base::probe!( + class = "persona.engine.admitted", + request = ?request, + incarnation = incarnation, + persona = %self.persona, + one_off = self.one_off, + queue_depth = queue_depth, + prompt_tokens = prompt_tokens, + since_submit_ms = since_submit_ms, + "the driver took a turn into its queue" + ), + At::FrameStarted { since_admit_ms, reused_tokens, prompt_tokens, switched } => continuum_base::probe!( + class = "persona.engine.frame_started", + request = ?request, + incarnation = incarnation, + persona = %self.persona, + one_off = self.one_off, + since_admit_ms = since_admit_ms, + reused_tokens = reused_tokens, + prompt_tokens = prompt_tokens, + switched = switched, + "a turn's first frame began" + ), + At::Infeasible { prompt_tokens, capacity } => continuum_base::probe!( + class = "persona.engine.infeasible", + request = ?request, + incarnation = incarnation, + persona = %self.persona, + one_off = self.one_off, + prompt_tokens = prompt_tokens, + capacity = capacity, + "a turn refused at the door: its prompt leaves no room in one stream" + ), + At::Refused { since_admit_ms, reason } => continuum_base::probe!( + class = "persona.engine.refused", + request = ?request, + incarnation = incarnation, + persona = %self.persona, + one_off = self.one_off, + since_admit_ms = since_admit_ms, + reason = %reason, + "a turn ended without an answer" + ), + At::FirstProgress { since_admit_ms, step_ms, prefill } => continuum_base::probe!( + class = "persona.engine.first_progress", + request = ?request, + incarnation = incarnation, + persona = %self.persona, + one_off = self.one_off, + since_admit_ms = since_admit_ms, + step_ms = step_ms, + prefill = prefill, + "a turn's first step succeeded natively" + ), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches (Codex, review of d3f24526ab): a first frame that blocks or fails reported as + // progress, and progress reported more than once on a turn of many chunks. + #[test] + fn a_failed_first_step_starts_without_progress_and_progress_is_reported_once() { + let mut failed = Milestones::default(); + assert!(failed.start(), "her first frame begins"); + assert!(!failed.step(false), "a failed first chunk is not progress"); + assert!(!failed.start(), "the start is reported once"); + + let mut turn = Milestones::default(); + assert!(turn.start()); + let reported: Vec = [true, true, true].into_iter().map(|ok| turn.step(ok)).collect(); + assert_eq!(reported, [true, false, false], "a multi-chunk turn reports its first progress once"); + } +} diff --git a/core/continuum-engine/src/inference/in_process_engine.rs b/core/continuum-engine/src/inference/in_process_engine.rs index f308772f7b..0a81205570 100644 --- a/core/continuum-engine/src/inference/in_process_engine.rs +++ b/core/continuum-engine/src/inference/in_process_engine.rs @@ -168,6 +168,10 @@ impl InProcessEngine { #[async_trait] impl LlamaServerControl for InProcessEngine { + fn stream_layout(&self) -> crate::inference::llama_server::StreamLayout { + crate::inference::llama_server::StreamLayout::PersonaScheduler + } + async fn active_model(&self) -> Result, LlamaServerError> { Ok(self.loaded.lock().await.as_ref().map(|loaded| &loaded.model_id).cloned()) } diff --git a/core/continuum-engine/src/inference/llama_server.rs b/core/continuum-engine/src/inference/llama_server.rs index 1006ac77e4..9998e9c7c1 100644 --- a/core/continuum-engine/src/inference/llama_server.rs +++ b/core/continuum-engine/src/inference/llama_server.rs @@ -66,6 +66,8 @@ use smoke::{ scratch_slot_for, smoke_answer_tokens, smoke_attempt, smoke_attempt_verdict, smoke_seat, smoke_verdict, SmokeCap, SmokeSeat, SmokeVerdict, }; +mod stream_layout; +pub use stream_layout::StreamLayout; mod target; pub use target::{ cold_expert_offload_ot, main_lane_placement, placement_from_config, serving_pool_kind, AdapterEntry, diff --git a/core/continuum-engine/src/inference/llama_server/control.rs b/core/continuum-engine/src/inference/llama_server/control.rs index 1d2676313d..dd9a432327 100644 --- a/core/continuum-engine/src/inference/llama_server/control.rs +++ b/core/continuum-engine/src/inference/llama_server/control.rs @@ -215,6 +215,8 @@ pub enum EngineRetirementError { /// fake to exercise the pure reconcile decision without a live process. #[async_trait] pub trait LlamaServerControl: Send + Sync { + fn stream_layout(&self) -> StreamLayout; + /// Scoped physical paging uncertainty requires the normal owned-engine /// replacement path even when model identity and HTTP health are unchanged. fn paging_recovery_required(&self) -> bool { diff --git a/core/continuum-engine/src/inference/llama_server/control_impl.rs b/core/continuum-engine/src/inference/llama_server/control_impl.rs index 696b98a923..9c3d2b54ed 100644 --- a/core/continuum-engine/src/inference/llama_server/control_impl.rs +++ b/core/continuum-engine/src/inference/llama_server/control_impl.rs @@ -2,6 +2,10 @@ use super::*; #[async_trait] impl LlamaServerControl for LlamaServerProcess { + fn stream_layout(&self) -> crate::inference::llama_server::StreamLayout { + crate::inference::llama_server::StreamLayout::Roster + } + fn paging_recovery_required(&self) -> bool { crate::inference::slots::directory() .endpoint(&self.root) diff --git a/core/continuum-engine/src/inference/llama_server/stream_layout.rs b/core/continuum-engine/src/inference/llama_server/stream_layout.rs new file mode 100644 index 0000000000..7f7346eae0 --- /dev/null +++ b/core/continuum-engine/src/inference/llama_server/stream_layout.rs @@ -0,0 +1,51 @@ +//! Physical sequences charged when fitting a serving pool. +#[derive(Debug, Copy, Clone)] +pub enum StreamLayout { + Roster, + PersonaScheduler, +} + +impl StreamLayout { + pub fn sequences(self, roster: u32) -> u32 { + match self { + Self::Roster => roster.max(1), + Self::PersonaScheduler => continuum_persona_llama::STREAMS as u32, + } + } + + pub fn minimum_window(self, roster_minimum: u32) -> u32 { + match self { + Self::Roster => roster_minimum, + Self::PersonaScheduler => 0, + } + } + + pub fn window(self, pool: u64, roster: u32, trained: u32) -> u32 { + let share = pool / u64::from(self.sequences(roster)); + match self { + Self::Roster => share.min(u64::from(u32::MAX)) as u32, + // The pinned native context pads each physical stream to 256 tokens. + Self::PersonaScheduler => { + let tokens = share.min(u64::from(trained)) as u32; + tokens - tokens % 256 + } + } + } +} + +#[cfg(test)] +mod tests { + use super::StreamLayout; + + #[test] + fn native_pool_charges_two_streams_and_fits_native_padding() { + let layout = StreamLayout::PersonaScheduler; + for roster in [1, 5] { + assert_eq!(layout.sequences(roster), 2); + assert_eq!(layout.window(511, roster, 98_304), 0); + assert_eq!(layout.window(121_600, roster, 32_767), 32_512); + assert_eq!(layout.window(121_600, roster, 98_304), 60_672); + assert_eq!(layout.window(121_600, roster, 32_768), 32_768); + } + } +} diff --git a/core/continuum-engine/src/inference/llama_server/tests.rs b/core/continuum-engine/src/inference/llama_server/tests.rs index 3ab581540f..03841eeda5 100644 --- a/core/continuum-engine/src/inference/llama_server/tests.rs +++ b/core/continuum-engine/src/inference/llama_server/tests.rs @@ -150,6 +150,10 @@ impl FakeControl { #[async_trait] impl LlamaServerControl for FakeControl { + fn stream_layout(&self) -> crate::inference::llama_server::StreamLayout { + crate::inference::llama_server::StreamLayout::Roster + } + fn owned_serving_target(&self) -> Option { self.verified_launch.clone() } diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs b/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs index be3d129ece..7125d412f2 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs @@ -153,18 +153,37 @@ pub(super) struct ParsedTurn { pub(super) tool_calls: Option>, } +/// Native generation output and the effective stop set used to produce it. +pub(super) struct GeneratedTurn<'a> { + pub(super) written: &'a str, + pub(super) tokens: usize, + pub(super) end: GenerationEnd, + pub(super) stops: &'a [String], +} + impl ParsedTurn { /// A turn that kept no text and no call, told apart by its raw tail and the stop it ended on: a /// stop string firing where her call began, the model ending inside its thinking, or a call the /// parse dropped (Aiko, 20 turns from 15:36Z 2026-11-19, text 0, reasoning only). - pub(super) fn probe_if_empty(&self, written: &str, tokens: usize, end: GenerationEnd, stops: &[String]) { + pub(super) fn probe_if_empty(&self, output: GeneratedTurn<'_>, request: &TextGenerationRequest) { + let GeneratedTurn { written, tokens, end, stops } = output; if !self.text.is_empty() || self.tool_calls.as_ref().is_some_and(|calls| !calls.is_empty()) { return; } + // Diagnostic only: correlate a Qwen function marker with this render's own request. + // A marker in generated text is never authority to dispatch a call. + let marker = written.rsplit_once("')) + .map(|(name, _)| name) + .filter(|name| !name.is_empty() && name.len() <= 128 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"/._-".contains(&b))); + let offered = marker.map(|name| request.tools.as_deref().into_iter().flatten() + .chain(request.tail_tools.as_deref().into_iter().flatten()).any(|tool| tool.name == name)); let chars: Vec = written.chars().collect(); let tail: String = chars[chars.len().saturating_sub(160)..].iter().collect(); continuum_base::probe!( class = "inference.turn.wrote_nothing", + persona = ?request.persona_id, + function_marker = ?marker, + offered_on_request = ?offered, tokens = tokens as u64, end = ?end, stop = ?stops.iter().find(|stop| written.ends_with(stop.as_str())), diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs index 990f4c3e88..1a0642ce96 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs @@ -135,6 +135,8 @@ impl AIProviderAdapter for LlamaCppAdapter { request: TextGenerationRequest, dispatched: crate::ai::adapter::Dispatched, ) -> Result { + // The monotonic origin of every later transition's `since_enter` (`inference.generate.enter`). + let entered = Instant::now(); let allocation = self.allocation()?; // Her think term: a stated zero budget renders no thinking; any other budget is bounded by // the template's own thinking tags below; none stated is the model's default. @@ -237,6 +239,7 @@ impl AIProviderAdapter for LlamaCppAdapter { class = "inference.generate.enter", model = request.model.as_deref().unwrap_or("?"), // unwrap_or: the probe names an unnamed model "?" persona_id = request.persona_id.as_deref().unwrap_or(""), // unwrap_or: a request for no persona probes an empty id + request = ?request.request_id.as_deref(), msg_count = request.messages.len(), max_tokens = ?request.max_tokens, has_system_prompt = request.system_prompt.is_some(), @@ -380,6 +383,7 @@ impl AIProviderAdapter for LlamaCppAdapter { let stable_for_blocking = stable_prefix.clone(); let stop_for_closure = stop_owned.clone(); let sampling_for_closure = sampling.clone(); + let request_for_blocking = request.request_id.clone(); // Parse the wire-format persona_id (Option on the public // request type) to Option for the typed scheduler API. A // malformed UUID drops to None rather than failing the request — @@ -411,7 +415,16 @@ impl AIProviderAdapter for LlamaCppAdapter { let genes_for_closure = requested_genes; continuum_base::time_probe!( "inference.forward.text", - tokio::task::spawn_blocking(move || { + async move { + let answer = tokio::task::spawn_blocking(move || { + // Brackets for the wait between entry and the engine's admission: a full + // blocking pool delays this line, a gene load delays the next. + continuum_base::probe!( + class = "inference.generate.worker_started", + request = ?request_for_blocking, + since_enter = ?entered.elapsed(), + "the blocking worker began this generation" + ); let stop_refs: Vec<&str> = stop_for_closure.iter().map(|s| s.as_str()).collect(); // Page in each requested gene (idempotent) before generation. @@ -420,21 +433,29 @@ impl AIProviderAdapter for LlamaCppAdapter { for (id, path, _) in &genes_for_closure { backend_for_blocking.ensure_adapter(id, path)?; } + continuum_base::probe!( + class = "inference.generate.genes_ready", + request = ?request_for_blocking, + genes = genes_for_closure.len(), + since_enter = ?entered.elapsed(), + "her genes are loaded for this generation" + ); let active_loras: Vec<(String, f32)> = genes_for_closure .iter() .map(|(id, _, scale)| (id.clone(), *scale)) .collect(); - backend_for_blocking.generate_for_persona( - allocation, persona_id, - crate::inference::backends::llamacpp::TurnPrompt { text: &prompt_for_blocking, stable_prefix: stable_for_blocking.as_deref() }, + backend_for_blocking.submit_for_persona( + allocation, persona_id, + crate::inference::backends::llamacpp::TurnPrompt { text: &prompt_for_blocking, stable_prefix: stable_for_blocking.as_deref(), request: request_for_blocking.as_deref() }, max_tokens, sampling_for_closure, &stop_refs, &active_loras, ) - }) + }).await.map_err(|e| format!("generate task panicked: {e}"))??; + answer.collect().await + } ) - .map_err(|e| format!("generate task panicked: {e}"))? } else { // Multimodal path: bypass the scheduler — media tokens have // a fixed positional layout the scheduler can't interleave @@ -511,7 +532,8 @@ impl AIProviderAdapter for LlamaCppAdapter { let (text, reasoning, tool_calls) = match &chat_render { Some((render, _)) => match super::chat_turn::parse_turn(render, &written, end) { Ok(turn) => { - turn.probe_if_empty(&written, tokens, end, &stop_owned); + let output = super::chat_turn::GeneratedTurn { written: &written, tokens, end, stops: &stop_owned }; + turn.probe_if_empty(output, &request); (turn.text, turn.reasoning, turn.tool_calls) } Err(refused) => return Err(refused.to_string()), diff --git a/core/continuum-flow/src/flow.rs b/core/continuum-flow/src/flow.rs index 6ddb4dfffb..790bb6c6d2 100644 --- a/core/continuum-flow/src/flow.rs +++ b/core/continuum-flow/src/flow.rs @@ -7,6 +7,7 @@ use crate::scheduler::{Aging, Decision, Dropped, Scheduler, Ticket}; use crate::Qos; use std::collections::HashMap; use std::hash::Hash; +use std::future::Future; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use tokio::sync::{mpsc, oneshot, watch}; @@ -94,24 +95,29 @@ impl Flow { /// Queue work for `owner` at `qos`; resolves when it may start, or at once with why it left /// the queue without running (`Refused::Dropped`: superseded by the owner's newer work, or /// shed from a full utility/background queue), or `Refused::Stopped` if the dispatcher has. - pub async fn submit(&self, owner: K, qos: Qos) -> Result { + pub fn submit(&self, owner: K, qos: Qos) -> impl Future> + Send + 'static { let ticket = Ticket(self.tickets.fetch_add(1, Ordering::Relaxed)); let (start, started) = oneshot::channel(); - self.events.send(Event::Submit { ticket, owner, qos, start }).map_err(|_| Refused::Stopped)?; - let mut pending = Pending { ticket, events: self.events.clone(), armed: true }; - let outcome = started.await.map_err(|_| Refused::Stopped)?; - pending.armed = false; - let yield_asked = outcome.map_err(Refused::Dropped)?; - let events = self.events.clone(); - Ok(Grant { - ticket, - events: Box::new(move |t| { - let _ = events.send(Event::Release(t)); // a stopped dispatcher has nothing to release - }), - yield_asked, - }) + // Enqueue now. Observing the start event later requires no worker of its own. + let queued = self.events.send(Event::Submit { ticket, owner, qos, start }).map_err(|_| Refused::Stopped); + let mut pending = Pending { ticket, events: self.events.clone(), armed: queued.is_ok() }; + async move { + queued?; + let outcome = started.await.map_err(|_| Refused::Stopped)?; + let events = pending.events.clone(); + pending.armed = false; + // Move the entire cancellation guard into the completion handle. + drop(pending); + let yield_asked = outcome.map_err(Refused::Dropped)?; + Ok(Grant { + ticket, + events: Box::new(move |t| { + let _ = events.send(Event::Release(t)); // a stopped dispatcher has nothing to release + }), + yield_asked, + }) + } } - /// The capacity changed (an engine relaunched with another slot count). pub fn resize(&self, capacity: usize) { let _ = self.events.send(Event::Resize(capacity)); // a stopped dispatcher has no capacity diff --git a/core/continuum-flow/src/stage.rs b/core/continuum-flow/src/stage.rs index f61a726afd..c33cdbb526 100644 --- a/core/continuum-flow/src/stage.rs +++ b/core/continuum-flow/src/stage.rs @@ -237,11 +237,12 @@ pub fn spawn_stage(mut stage: S, capacity: Capacity) -> (StageInput = Flow::spawn(1, aging()); let _busy = flow.submit("aris", Qos::Work).await; - let first = tokio::spawn({ - let flow = flow.clone(); - async move { flow.submit("aiko", Qos::Work).await.err() } - }); - tokio::task::yield_now().await; - let _second = tokio::spawn({ - let flow = flow.clone(); - async move { flow.submit("aiko", Qos::Work).await.is_ok() } - }); - let why = tokio::time::timeout(Duration::from_secs(1), first).await; - assert!(matches!(why, Ok(Ok(Some(Refused::Dropped(Dropped::Superseded))))), "{why:?}"); + let first = flow.submit("aiko", Qos::Work); + let second = flow.submit("aiko", Qos::Work); + assert!(matches!(first.await, Err(Refused::Dropped(Dropped::Superseded)))); + drop(_busy); + assert!(second.await.is_ok()); } // what this catches: a dispatcher that polls. It sleeps until the next aging step, or forever @@ -522,3 +516,21 @@ async fn a_submission_wakes_a_producer_held_by_a_stalled_sink_and_the_drain_lose worker.join().await.expect("test: the worker drained"); assert_eq!(*got.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 2, 3, 4], "the cancelled drain lost nothing and kept the order"); // test: plain data } + +#[test] +fn stopping_executor_before_first_poll_closes_intake() { + struct Wake; + impl Stage for Wake { + type Input = (); + const QOS: Qos = Qos::Utility; + async fn handle(&mut self, (): ()) {} + } + + let runtime = tokio::runtime::Builder::new_current_thread().build().expect("test: current-thread runtime"); + let (input, _worker) = { + let _entered = runtime.enter(); + spawn_stage(Wake, Capacity::latest()) + }; + drop(runtime); + assert_eq!(input.push(()), Err(crate::PushError::Stopped(()))); +} diff --git a/core/continuum-genome/Cargo.toml b/core/continuum-genome/Cargo.toml index 7c94eb1ca0..7c9a794e30 100644 --- a/core/continuum-genome/Cargo.toml +++ b/core/continuum-genome/Cargo.toml @@ -11,6 +11,7 @@ repository = "https://github.com/CambrianTech/continuum" # re-exports `genome` under its old path. [dependencies] +continuum-flow = { path = "../continuum-flow" } continuum-process = { path = "../continuum-process" } continuum-kernel = { path = "../continuum-kernel" } # the ORM derive names it (recall decisions) continuum-engine = { path = "../continuum-engine" } diff --git a/core/continuum-genome/src/genome/gene_residency.rs b/core/continuum-genome/src/genome/gene_residency.rs index 16c0d77ad9..fc3c624ac4 100644 --- a/core/continuum-genome/src/genome/gene_residency.rs +++ b/core/continuum-genome/src/genome/gene_residency.rs @@ -20,10 +20,10 @@ //! Probes: `genome.page` (gene, direction, bytes, ms) and `genome.page.failed`. use std::collections::{BTreeSet, HashMap}; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; pub mod catalog; +mod reconcile; use parking_lot::Mutex; use uuid::Uuid; @@ -119,8 +119,7 @@ impl State { #[derive(Default)] pub struct GeneResidency { state: Mutex, - reconciling: AtomicBool, - again: AtomicBool, + reconcile_worker: reconcile::Worker, } impl GeneResidency { @@ -147,28 +146,6 @@ impl GeneResidency { } } - /// Bring the engine's catalog in and page back in what her minds run, off the request path. - /// Coalesced: a reconcile asked for while one runs runs once more after it. - pub fn schedule_reconcile(self: &Arc) { - let Ok(runtime) = tokio::runtime::Handle::try_current() else { - return; // no runtime (a sync test): nothing to page, and the engine pages in on demand - }; - if self.reconciling.swap(true, Ordering::AcqRel) { - self.again.store(true, Ordering::Release); - return; - } - let me = Arc::clone(self); - runtime.spawn(async move { - loop { - me.reconcile().await; - if !me.again.swap(false, Ordering::AcqRel) { - break; - } - } - me.reconciling.store(false, Ordering::Release); - }); - } - async fn reconcile(&self) { let seats = match gene_seats().await { Ok(seats) => seats, diff --git a/core/continuum-genome/src/genome/gene_residency/reconcile.rs b/core/continuum-genome/src/genome/gene_residency/reconcile.rs new file mode 100644 index 0000000000..3daabc6738 --- /dev/null +++ b/core/continuum-genome/src/genome/gene_residency/reconcile.rs @@ -0,0 +1,53 @@ +//! A turn changes the desired residency. One queued wake covers all changes +//! since the worker last read the phenotype state. +use super::GeneResidency; +use continuum_flow::{spawn_stage, Capacity, Overflow, PushError, Qos, Stage, StageInput, StageWorker}; +use parking_lot::Mutex; +use std::sync::{Arc, Weak}; + +#[derive(Default)] +pub(super) struct Worker(Mutex>); + +struct Running { + input: StageInput<()>, + _worker: StageWorker<()>, +} + +struct Reconcile(Weak); + +impl Stage for Reconcile { + type Input = (); + const QOS: Qos = Qos::Utility; + const OVERFLOW: Overflow = Overflow::KeepNewest; + + async fn handle(&mut self, (): ()) { + if let Some(owner) = self.0.upgrade() { + owner.reconcile().await; + } + } +} + +impl GeneResidency { + pub fn schedule_reconcile(self: &Arc) { + let mut running = self.reconcile_worker.0.lock(); + if let Some(stage) = running.as_ref() { + match stage.input.push(()) { + Ok(_) | Err(PushError::Full(())) => return, + Err(PushError::Stopped(())) => continuum_base::probe!( + class = "genome.page.worker_stopped", + "replacing the stopped gene residency worker and resubmitting its wake" + ), + } + } + if let Err(error) = tokio::runtime::Handle::try_current() { + continuum_base::probe!(class = "genome.page.worker_unavailable", error = %error, + "gene reconciliation needs a running executor"); + return; + } + let (input, worker) = spawn_stage(Reconcile(Arc::downgrade(self)), Capacity::latest()); + if let Err(PushError::Stopped(())) = input.push(()) { + continuum_base::probe!(class = "genome.page.worker_stopped", "executor stopped during gene worker startup"); + } + *running = Some(Running { input, _worker: worker }); + } +} diff --git a/core/continuum-kernel/src/routing/probe_file_sink.rs b/core/continuum-kernel/src/routing/probe_file_sink.rs index cb67d5d684..9023a52a59 100644 --- a/core/continuum-kernel/src/routing/probe_file_sink.rs +++ b/core/continuum-kernel/src/routing/probe_file_sink.rs @@ -70,7 +70,6 @@ //! `ProbeRouterLayer` already uses. Not load-bearing today. use std::collections::HashSet; -use std::fs::OpenOptions; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::Mutex; @@ -87,24 +86,23 @@ use super::probe_span_meta::{ }; /// Env var carrying a directory path for rolling JSONL probe capture. -/// Daily rotation, last `DEFAULT_MAX_LOG_FILES` retained, disk usage +/// Size rotation under `capped_appender`'s one limit, disk usage /// bounded by design. The ONLY env-based entry point — per /// `[[auto-clean-is-structural-not-operational]]` any substrate writer /// that grows incrementally MUST auto-clean structurally. /// -/// Single-file mode is reachable in-code via -/// [`JsonlProbeFileSink::new`] for tests + explicit forensic capture; -/// it is deliberately NOT exposed as an env var to keep operators on -/// the bounded-by-design path. +/// There is no single-file mode: every sink rolls (the unbounded constructor +/// had no production caller and is deleted, #6208). pub const ENV_PROBE_DIR: &str = "CONTINUUM_PROBE_DIR"; /// Env var carrying the comma-separated class filter. Empty/unset = /// all classes pass through. pub const ENV_PROBE_CLASSES: &str = "CONTINUUM_PROBE_CLASSES"; -/// Default retention for the rolling-file mode — last 7 days. Matches -/// the fmt-layer rolling retention so operators learn one number. -pub const DEFAULT_MAX_LOG_FILES: usize = 7; +/// Generations the rolling sink keeps: the appender's own `KEEP`, the number the broker's +/// rotation pool budgets against, never a second count (this sink kept 7 against its 8). +pub use crate::routing::capped_appender::KEEP as DEFAULT_MAX_LOG_FILES; + /// The live probe ledger; the rotation pool that governs its generations names it too. pub const PROBE_LEDGER_FILE: &str = "continuum-probes.jsonl"; @@ -116,15 +114,10 @@ pub const PROBE_LEDGER_FILE: &str = "continuum-probes.jsonl"; /// in-process, this one persists to disk. Both visit the same /// tracing event independently; neither blocks the other. pub struct JsonlProbeFileSink { - /// On-disk target. In single-file mode this is the file path; in - /// rolling mode this is the directory holding dated rotation files. - /// Same field surfaces both modes so logging / tests don't need to - /// branch on the mode. + /// On-disk target: the directory holding the dated rotation files. target: PathBuf, - /// `Box` wraps whichever underlying writer the - /// constructor chose — `BufWriter` for single-file mode, - /// `BufWriter` for rolling mode. Identical - /// hot-path code regardless of mode. + /// `Box`: `BufWriter` in + /// production, any writer in tests (a disk that refuses writes). writer: Mutex>, /// Empty set = no filter (all classes pass). Non-empty = only /// classes in this set get persisted. @@ -179,41 +172,10 @@ impl std::error::Error for ProbeFileSinkError { } impl JsonlProbeFileSink { - /// Construct a sink writing to a single file at `path`. - /// **Single-file / forensic mode** — append-only, no rotation, - /// grows unbounded. Use [`new_rolling`](Self::new_rolling) for - /// production captures per the - /// `[[auto-clean-is-structural-not-operational]]` doctrine. - /// - /// Empty `allowed_classes` = all classes pass. File is opened in - /// append mode (created if missing). Buffer flushes per line via - /// `BufWriter::new`'s default + explicit `flush` after each event - /// (chosen for `tail -f`-ability — operators expect the line to - /// appear immediately, not after the buffer fills). - pub fn new>( - path: P, - allowed_classes: HashSet, - ) -> Result { - let path = path.as_ref().to_path_buf(); - let file = OpenOptions::new() - .create(true) - .append(true) - .open(&path) - .map_err(|source| ProbeFileSinkError::OpenFailed { - path: path.clone(), - source, - })?; - Ok(Self { - target: path, - writer: Mutex::new(Box::new(BufWriter::new(file))), - allowed_classes, - }) - } - /// Construct a sink writing to a **rotating** JSONL file under - /// `dir`. **Rolling / production mode.** Daily rotation, retains - /// last `max_log_files` days (default - /// [`DEFAULT_MAX_LOG_FILES`] when called via env). Disk usage + /// `dir`, rotated at `capped_appender::MAX_LOG_BYTES` and keeping + /// `max_log_files` generations (`DEFAULT_MAX_LOG_FILES`, the appender's `KEEP`: the bound the + /// `PressureBroker`'s rotation pool budgets against. Disk usage /// bounded by design. /// /// Implements `[[auto-clean-is-structural-not-operational]]`: @@ -239,14 +201,9 @@ impl JsonlProbeFileSink { // Size-rotated, not clock-rotated — see [`crate::routing::capped_appender`]. The // probe stream is the HIGHEST-volume writer in the substrate (one JSON line per // load-bearing decision across every tokio task), so a clock-based "bound" is even - // less of one here than for the fmt log. `max_log_files` keeps its meaning: how many - // generations survive. What changes is that a generation now has a size. - let appender = crate::routing::capped_appender::CappedAppender::with_limits( - &dir, - PROBE_LEDGER_FILE, - crate::routing::capped_appender::MAX_LOG_BYTES, - max_log_files, - ) + // less of one here than for the fmt log. A generation has the appender's size; how many + // survive is `max_log_files` (`DEFAULT_MAX_LOG_FILES` is the appender's `KEEP`). + let appender = crate::routing::capped_appender::CappedAppender::with_limits(&dir, PROBE_LEDGER_FILE, crate::routing::capped_appender::MAX_LOG_BYTES, max_log_files) .map_err(|source| ProbeFileSinkError::OpenFailed { path: dir.clone(), source, @@ -260,8 +217,7 @@ impl JsonlProbeFileSink { /// Construct from `CONTINUUM_PROBE_DIR` + `CONTINUUM_PROBE_CLASSES`. /// The ONLY env-based entry point — rolling mode, structural - /// auto-clean, bounded disk usage. Single-file mode is reachable - /// only via [`new`](Self::new) in-code for tests + forensic capture. + /// auto-clean, bounded disk usage. /// /// Returns `Err(EnvVarUnset)` if `CONTINUUM_PROBE_DIR` is missing — /// callers treat that as "sink intentionally disabled, install no @@ -277,24 +233,28 @@ impl JsonlProbeFileSink { .filter(|c| !c.is_empty()) .collect::>() }) - .unwrap_or_default(); + .unwrap_or_default(); // JUSTIFIED: an unset class filter is documented as "every class passes", not an unknown Self::new_rolling(dir, allowed_classes, DEFAULT_MAX_LOG_FILES) } - /// The on-disk target the sink writes to. In single-file mode this - /// is the file path; in rolling mode this is the directory holding - /// the dated rotation files. Useful for tests + boot logging. + /// The directory the sink rolls its dated files in. Useful for + /// tests + boot logging. pub fn target(&self) -> &Path { &self.target } /// Write one ProbeEvent as a JSONL line. Flushes immediately so - /// `tail -f` works. Errors are dropped silently — a sink that - /// can't write its line to disk SHOULDN'T panic the persona - /// service loop. The next event tries again; persistent failures - /// surface via the file's apparent staleness, not a substrate - /// crash. + /// `tail -f` works. A line it cannot write never fails its caller (a + /// probe is telemetry); it is counted in `continuum_base::probe_writes`, + /// so a reader that claims records reached the log says how many did not. fn write_one(&self, captured_at_ms: u64, ev: &ProbeEvent) { + if !self.wrote(captured_at_ms, ev) { + continuum_base::probe_writes::count_failure(); + } + } + + /// Whether the line was serialized, written and flushed. + fn wrote(&self, captured_at_ms: u64, ev: &ProbeEvent) -> bool { #[derive(Serialize)] struct OnDiskEnvelope<'a> { captured_at_ms: u64, @@ -313,15 +273,13 @@ impl JsonlProbeFileSink { fields: &ev.fields, }; - let Ok(line) = serde_json::to_string(&envelope) else { - return; + let Ok(line) = serde_json::to_string(&envelope) else { // disk format: the JSONL line this sink exists to write + return false; }; let Ok(mut guard) = self.writer.lock() else { - return; // poisoned lock — sink is effectively dead; don't crash callers + return false; // poisoned lock — sink is effectively dead; don't crash callers }; - if writeln!(guard, "{line}").is_ok() { - let _ = guard.flush(); - } + writeln!(guard, "{line}").and_then(|()| guard.flush()).is_ok() } } diff --git a/core/continuum-kernel/src/routing/probe_file_sink/tests.rs b/core/continuum-kernel/src/routing/probe_file_sink/tests.rs index 1d7249e75f..e47676fb81 100644 --- a/core/continuum-kernel/src/routing/probe_file_sink/tests.rs +++ b/core/continuum-kernel/src/routing/probe_file_sink/tests.rs @@ -6,12 +6,18 @@ use tempfile::tempdir; use tracing_subscriber::prelude::*; - /// Helper: read every JSONL line from the sink path back as - /// parsed JSON Values. Lets tests assert on field presence / - /// content without re-implementing the on-disk shape. - fn read_jsonl(path: &Path) -> Vec { + /// Helper: read every JSONL line the rolling sink wrote under `dir` + /// back as parsed JSON Values (none when it wrote nothing). Lets tests + /// assert on field presence / content without re-implementing the + /// on-disk shape. + fn read_jsonl(dir: &Path) -> Vec { + let rolled = std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| path.file_name().is_some_and(|name| name.to_string_lossy().starts_with("continuum-probes"))); + let Some(rolled) = rolled else { return Vec::new() }; let mut content = String::new(); - File::open(path) + File::open(rolled) .unwrap() .read_to_string(&mut content) .unwrap(); @@ -47,9 +53,9 @@ #[test] fn unfiltered_sink_persists_every_class() { let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); - let sink = JsonlProbeFileSink::new(&path, HashSet::new()).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -82,12 +88,12 @@ // NOT `personality.foo` (the dot guard prevents partial- // word collisions). Per the docstring's rule 3. let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); let mut allowed = HashSet::new(); allowed.insert("persona".to_string()); - let sink = JsonlProbeFileSink::new(&path, allowed).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, allowed, DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -119,12 +125,12 @@ // `CONTINUUM_PROBE_CLASSES=*` to deliberately request the // firehose. let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); let mut allowed = HashSet::new(); allowed.insert("*".to_string()); - let sink = JsonlProbeFileSink::new(&path, allowed).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, allowed, DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -146,13 +152,13 @@ // picture. The filter must support both shapes in the same // HashSet without rule contention. let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); let mut allowed = HashSet::new(); allowed.insert("cognition.analyze.parse".to_string()); // exact allowed.insert("persona.turn".to_string()); // namespace - let sink = JsonlProbeFileSink::new(&path, allowed).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, allowed, DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -208,12 +214,12 @@ #[test] fn class_filter_drops_unallowed_classes() { let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); let mut allowed = HashSet::new(); allowed.insert("persona.render.exit".to_string()); - let sink = JsonlProbeFileSink::new(&path, allowed).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, allowed, DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -236,9 +242,9 @@ // consumer, not a generic tracing forwarder. Keeps the // probe log signal-rich. let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); - let sink = JsonlProbeFileSink::new(&path, HashSet::new()).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -261,9 +267,9 @@ // command's execution." Mirrors the // `probe_event_carries_uri_chain` test in probe_router. let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); - let sink = JsonlProbeFileSink::new(&path, HashSet::new()).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -289,9 +295,9 @@ #[test] fn time_sync_span_close_persists_timing_to_jsonl() { let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); - let sink = JsonlProbeFileSink::new(&path, HashSet::new()).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -318,9 +324,9 @@ #[test] fn time_probe_span_close_persists_timing_to_jsonl() { let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); - let sink = JsonlProbeFileSink::new(&path, HashSet::new()).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -352,9 +358,9 @@ #[test] fn plain_span_close_does_not_persist_to_jsonl() { let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); - let sink = JsonlProbeFileSink::new(&path, HashSet::new()).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -396,9 +402,9 @@ use crate::routing::ProbeRouterLayer; let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); - let sink = JsonlProbeFileSink::new(&path, HashSet::new()).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); let router = ProbeRouterLayer::new(); let mut rx = router.subscribe("timing"); @@ -453,12 +459,12 @@ #[test] fn class_filter_applies_to_timing_spans() { let dir = tempdir().unwrap(); - let path = dir.path().join("probes.jsonl"); + let path = dir.path().to_path_buf(); let mut allowed = HashSet::new(); allowed.insert("persona.render.exit".to_string()); - let sink = JsonlProbeFileSink::new(&path, allowed).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(&path, allowed, DEFAULT_MAX_LOG_FILES).unwrap(); let subscriber = tracing_subscriber::registry() .with(crate::routing::UriCaptureLayer::new()) .with(sink); @@ -486,7 +492,7 @@ #[test] fn new_rolling_writes_to_dated_file_in_target_dir() { let dir = tempdir().unwrap(); - let sink = JsonlProbeFileSink::new_rolling(dir.path(), HashSet::new(), 7).unwrap(); + let sink = JsonlProbeFileSink::new_rolling(dir.path(), HashSet::new(), DEFAULT_MAX_LOG_FILES).unwrap(); // target() reports the DIRECTORY in rolling mode, not a file. assert_eq!(sink.target(), dir.path()); @@ -523,3 +529,27 @@ "expected probe class in rolled file, got: {content:?}" ); } + + /// A disk that refuses every write. + struct Refuses; + + impl std::io::Write for Refuses { + fn write(&mut self, _buf: &[u8]) -> std::io::Result { + Err(std::io::Error::other("disk full")) + } + fn flush(&mut self) -> std::io::Result<()> { + Err(std::io::Error::other("disk full")) + } + } + + // what this catches (Codex on #6208 at 162fbe5fa7): a probe line the sink could not write dropped + // silently, so a stop's settle claimed its records reached the log when none did. + #[test] + fn a_line_the_sink_cannot_write_is_counted() { + let sink = JsonlProbeFileSink { target: PathBuf::from("refuses"), writer: Mutex::new(Box::new(Refuses)), allowed_classes: HashSet::new() }; + let before = continuum_base::probe_writes::Reading::now(); + tracing::subscriber::with_default(tracing_subscriber::registry().with(sink), || { + continuum_base::probe!(class = "persona.engine.turn", "a turn row"); + }); + assert!(continuum_base::probe_writes::Reading::now().since(before) >= 1, "the refused write is counted"); + } diff --git a/core/continuum-persona-engine/src/engine.rs b/core/continuum-persona-engine/src/engine.rs index fd4f799225..ceb0859a64 100644 --- a/core/continuum-persona-engine/src/engine.rs +++ b/core/continuum-persona-engine/src/engine.rs @@ -111,6 +111,11 @@ where self.roles.active().map(Identified::persona) } + /// The units held across the active, staged and retiring roles. + pub fn units(&self) -> impl Iterator { + self.roles.units() + } + /// The active mind's own state (her tokens, her position), never the tier she runs on. pub fn active_mut(&mut self) -> Option<&mut U> { self.roles.active_mut() diff --git a/core/continuum-persona-engine/src/engine/tests.rs b/core/continuum-persona-engine/src/engine/tests.rs index 1717a35eff..41efbffd4f 100644 --- a/core/continuum-persona-engine/src/engine/tests.rs +++ b/core/continuum-persona-engine/src/engine/tests.rs @@ -243,6 +243,8 @@ fn a_refused_copy_out_is_finished_before_the_next_switch_and_given_back_once() { assert!(matches!(h.engine.finish_retirement(), Err(RetireError::CopyOut(_))), "still refused"); assert_eq!(h.engine.retiring(), Some(id(1)), "she stays in custody"); + let held: Vec<_> = h.engine.units().map(|mind| mind.id()).collect(); + assert_eq!(held, [id(2), id(1)], "both active and retiring minds remain in custody"); h.refuse.set(None); assert!(matches!(h.engine.finish_retirement(), Err(RetireError::Release(RetireRefusal::NotLanded { .. }))), "begun, not landed"); land_last(&h.moves); diff --git a/core/continuum-persona-engine/src/pipeline/roles.rs b/core/continuum-persona-engine/src/pipeline/roles.rs index fcbaebf43b..84581c117d 100644 --- a/core/continuum-persona-engine/src/pipeline/roles.rs +++ b/core/continuum-persona-engine/src/pipeline/roles.rs @@ -83,11 +83,11 @@ enum Retiring { Moving(InFlight), } -impl Retiring { - fn persona(&self) -> PersonaId { +impl Retiring { + fn unit(&self) -> &U { match self { - Self::AwaitingCopyOut(unit) => unit.persona(), - Self::Moving(moving) => moving.unit.persona(), + Self::AwaitingCopyOut(unit) => unit, + Self::Moving(moving) => &moving.unit, } } } @@ -115,6 +115,13 @@ impl Roles { self.active.as_ref() } + /// All units this Core owns, including those in flight. + pub fn units(&self) -> impl Iterator { + self.active.iter() + .chain(self.next.iter().map(|next| &next.unit)) + .chain(self.retiring.iter().map(Retiring::unit)) + } + /// Mutable access to the active mind only: decoding touches nobody else. pub fn active_mut(&mut self) -> Option<&mut U> { self.active.as_mut() @@ -125,7 +132,7 @@ impl Roles { } pub fn retiring(&self) -> Option { - self.retiring.as_ref().map(Retiring::persona) + self.retiring.as_ref().map(|role| role.unit().persona()) } /// The exact copy-out to begin for the mind awaiting it (her persona, epoch, direction out): the diff --git a/core/continuum-persona-engine/src/turn.rs b/core/continuum-persona-engine/src/turn.rs index 0ac78dbc5a..e0f997f076 100644 --- a/core/continuum-persona-engine/src/turn.rs +++ b/core/continuum-persona-engine/src/turn.rs @@ -36,9 +36,27 @@ pub enum Prefill { /// (`Append { from: len - 1 }`, after the tier drops that one position). An empty prompt cannot be /// sampled from and restarts, as does a mind with nothing held. pub fn plan(held: History<'_, B>, turn: History<'_, B>) -> Prefill { - let extends = held.basis == turn.basis && !held.tokens.is_empty() && turn.tokens.starts_with(held.tokens); - if !extends || turn.tokens.is_empty() { - return Prefill::Restart; + held.compare(&turn).prefill +} + +/// One comparison of the native token vectors, used for planning and accounting. +pub struct Compared { + pub shared: usize, + pub prefill: Prefill, +} + +pub fn common_prefix(a: &[i32], b: &[i32]) -> usize { + a.iter().zip(b).take_while(|(left, right)| left == right).count() +} + +impl History<'_, B> { + pub fn compare(&self, next: &History<'_, B>) -> Compared { + let shared = common_prefix(self.tokens, next.tokens); + let prefill = if shared > 0 && shared == self.tokens.len() && self.basis == next.basis { + Prefill::Append { from: shared.min(next.tokens.len() - 1) } + } else { + Prefill::Restart + }; + Compared { shared, prefill } } - Prefill::Append { from: held.tokens.len().min(turn.tokens.len() - 1) } } diff --git a/core/continuum-persona-llama/Cargo.toml b/core/continuum-persona-llama/Cargo.toml index 8cc103b351..6633a83265 100644 --- a/core/continuum-persona-llama/Cargo.toml +++ b/core/continuum-persona-llama/Cargo.toml @@ -15,8 +15,10 @@ name = "persona_switch" required-features = ["test-fixtures"] [dependencies] +continuum-base = { path = "../continuum-base" } # probe!: a refused decode reports what the engine held continuum-persona-engine = { path = "../continuum-persona-engine" } llama = { path = "../llama" } +tracing.workspace = true # probe! expands to tracing thiserror.workspace = true uuid.workspace = true diff --git a/core/continuum-persona-llama/src/unified_tier.rs b/core/continuum-persona-llama/src/unified_tier.rs index 100112b26d..f7ec5439c1 100644 --- a/core/continuum-persona-llama/src/unified_tier.rs +++ b/core/continuum-persona-llama/src/unified_tier.rs @@ -289,11 +289,26 @@ impl Execute for UnifiedTier<'_, '_> { for (offset, (i, &token)) in (0..count).zip(step.tokens.iter().enumerate()) { batch.push(token, step.from + offset, &[stream.seq()], step.logits_at_end && i == last); } - self.ctx.decode(&batch).map_err(|message| TierRefusal { - tier: TIER, - mind, - reason: "the engine refused her decode", - native: Native::Reported(message), + self.ctx.decode(&batch).map_err(|message| { + // The refusal says what the engine held when it refused (the M5, 2026-11-21: a cold + // 26-36k replay prefill refused with no KV slot ~31 s in; the cause is not yet known). + let occupied: Vec<(usize, Option, i32)> = + self.streams.iter().enumerate().map(|(at, held)| (at, *held, self.ctx.memory_seq_pos_max(stream_at(at).seq()))).collect(); + continuum_base::probe!( + class = "persona.engine.decode_refused", + persona = ?mind, + from = step.from, + tokens = count, + n_ctx = self.ctx.n_ctx(), + n_ctx_seq = self.ctx.n_ctx_seq(), + n_seq_max = self.ctx.n_seq_max(), + n_batch = self.ctx.n_batch(), + n_ubatch = self.ctx.n_ubatch(), + streams = ?occupied, + native = %message, + "the engine refused a decode: what it held then" + ); + TierRefusal { tier: TIER, mind, reason: "the engine refused her decode", native: Native::Reported(message) } })?; let landed = Rc::new(Cell::new(false)); self.in_flight = Some(Rc::clone(&landed)); diff --git a/core/continuum-serving/src/modules/serving_daemon/host_fit.rs b/core/continuum-serving/src/modules/serving_daemon/host_fit.rs index 1fe1089eeb..92f167f8b1 100644 --- a/core/continuum-serving/src/modules/serving_daemon/host_fit.rs +++ b/core/continuum-serving/src/modules/serving_daemon/host_fit.rs @@ -133,10 +133,10 @@ impl PoolFit { } /// The pool the engine launches with, in tokens. - pub(super) fn pool(self, sequences: u32) -> u64 { + pub(super) fn pool(self, sequences: u32, minimum_window: u32) -> u64 { match self { Self::Unmeasured { demand } | Self::Fits { demand, .. } => demand, - Self::Bounded { demand, fit, .. } => fit.max(u64::from(MIN_SERVE_CTX) * u64::from(sequences)).min(demand), + Self::Bounded { demand, fit, .. } => fit.max(u64::from(minimum_window) * u64::from(sequences)).min(demand), } } } @@ -203,11 +203,23 @@ mod tests { fn the_pool_is_the_demand_until_the_host_bounds_it() { let fp = crate::inference::planning::serving_plan::footprint::footprint_from_parts("m", 20 * GB, 262_144, true, None).expect("test: a footprint"); let host = |r| Rooms { host: Some(r), device: None }; - assert_eq!(pool_fit(100_000, Some(&fp), Rooms { host: None, device: None }, 0, 5, 262_144).pool(5), 100_000, "no reading: the demand stands"); + assert_eq!(pool_fit(100_000, Some(&fp), Rooms { host: None, device: None }, 0, 5, 262_144).pool(5, MIN_SERVE_CTX), 100_000, "no reading: the demand stands"); assert!(matches!(pool_fit(100_000, Some(&fp), host(room(60 * GB, 0, 0)), 0, 5, 262_144), PoolFit::Fits { .. })); let starved = pool_fit(100_000, Some(&fp), host(room(GB, 0, 0)), 0, 5, 262_144); assert!(matches!(starved, PoolFit::Bounded { fit: 0, by: Bound::Host(_), .. })); - assert_eq!(starved.pool(5), 5 * u64::from(MIN_SERVE_CTX), "never below one least window per sequence"); + assert_eq!(starved.pool(5, MIN_SERVE_CTX), 5 * u64::from(MIN_SERVE_CTX), "never below one least window per sequence"); + } + + #[test] + fn native_pool_requires_the_fixed_bytes_of_both_streams() { + use crate::inference::llama_server::StreamLayout; + let fp = crate::inference::planning::serving_plan::footprint::footprint_from_parts("m", 20 * GB, 262_144, true, None).expect("test: a footprint"); + let layout = StreamLayout::PersonaScheduler; + let sequences = layout.sequences(1); + let room = fp.weights_bytes + fp.compute_buffer_per_lane() * 3 / 2; + assert!(fp.window_within(room, 1) > 0); + let fit = pool_fit(48_000, Some(&fp), Rooms { host: None, device: Some(room) }, 0, sequences, fp.context_window); + assert_eq!(fit.pool(sequences, layout.minimum_window(MIN_SERVE_CTX)), 0); } // what this catches (the M5, 2026-11-14 01:22Z: the embedder's 186,908,672 B lease refused at @@ -220,6 +232,6 @@ mod tests { let fit = pool_fit(1_000_000, Some(&fp), rooms, 0, 5, 262_144); assert!(matches!(fit, PoolFit::Bounded { by: Bound::Device { room }, .. } if room == 25 * GB), "{fit:?}"); let host_only = pool_fit(1_000_000, Some(&fp), Rooms { device: None, ..rooms }, 0, 5, 262_144); - assert!(fit.pool(5) < host_only.pool(5), "the device's room is the smaller"); + assert!(fit.pool(5, MIN_SERVE_CTX) < host_only.pool(5, MIN_SERVE_CTX), "the device's room is the smaller"); } } diff --git a/core/continuum-serving/src/modules/serving_daemon/launch.rs b/core/continuum-serving/src/modules/serving_daemon/launch.rs index 66a58a0a0d..f9355f5c7a 100644 --- a/core/continuum-serving/src/modules/serving_daemon/launch.rs +++ b/core/continuum-serving/src/modules/serving_daemon/launch.rs @@ -2,6 +2,7 @@ use super::*; use crate::inference::planning::window_allocator::Measure; +use crate::inference::planning::MIN_SERVE_CTX; /// Owned inputs that passed the reconcile decision guards. The operation remains held /// through launch and is moved into the same asynchronous lifecycle task. @@ -47,7 +48,9 @@ impl ServingDaemonModule { /// beside `host_cache_bytes` of prompt cache, never more than the demand. pub(super) fn engine_pool(&self, model: &crate::model_registry::types::Model, served_ctx: u32, lanes: u32, host_cache_bytes: u64) -> EnginePool { let leased_in = LAST_LEASED_IN_PEAK.load(Ordering::Relaxed); - let sequences = self.seated().saturating_add(1).saturating_add(leased_in).max(lanes).max(1); + let roster = self.seated().saturating_add(1).saturating_add(leased_in).max(lanes).max(1); + let layout = self.server.stream_layout(); + let sequences = layout.sequences(roster); // Each lock is taken and released in its own statement: a guard made inside a call's // argument list lives to the end of the statement, so reading the budget there while // `seated_for` locks it again deadlocked the reconcile and wedged the core's boot (the M5, @@ -58,7 +61,7 @@ impl ServingDaemonModule { let footprint = footprint_for(model); // The size is the seated minds' need with the grants' growth margin; the plan's pool only // when no mind is remembered (`host_fit::need_with_growth`). - let demand = match host_fit::need_with_growth(&self.seated_claims(model), sequences, model.context_window) { + let demand = match host_fit::need_with_growth(&self.seated_claims(model), roster, model.context_window) { Some(need) => need, None => launch_pool(footprint.as_ref(), usable, served_ctx, lanes, sequences, model.context_window, seated), }; @@ -69,9 +72,9 @@ impl ServingDaemonModule { }; let rooms = host_fit::Rooms { host: self.host_room(released), device }; let fit = host_fit::pool_fit(demand, footprint.as_ref(), rooms, host_cache_bytes, sequences, model.context_window); - let pool = fit.pool(sequences); + let pool = fit.pool(sequences, layout.minimum_window(MIN_SERVE_CTX)); // `-c` is the CLI's `slots x per-slot`: the pool carried in that shape, not anyone's window. - let per_sequence = u32::try_from(pool / u64::from(sequences)).unwrap_or(u32::MAX); // unwrap_or: a pool over u32 x sequences is no real engine; the CLI caps it + let per_sequence = layout.window(pool, roster, model.context_window); EnginePool { per_sequence, sequences, fit } } @@ -248,6 +251,9 @@ impl ServingDaemonModule { lanes_bound = ?planned.plan.as_ref().map(|p| p.lanes_bound), plan_lanes = lanes, plan_window = served_ctx, + fitted_sequences = target.lanes, + fitted_window = target.context_window, + fitted_pool = engine_pool.tokens(), host_prompt_cache_mib, "reconcile launch requested from this plan: the engine relaunches only for a different model, genome, sight, KV decision, binary or a cache not yet on the shared pool", ); diff --git a/core/continuum-serving/src/modules/serving_daemon/tests.rs b/core/continuum-serving/src/modules/serving_daemon/tests.rs index 94b80fbab8..09ec98ca95 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests.rs @@ -84,6 +84,10 @@ impl FakeServer { #[async_trait] impl LlamaServerControl for FakeServer { + fn stream_layout(&self) -> crate::inference::llama_server::StreamLayout { + crate::inference::llama_server::StreamLayout::Roster + } + fn paging_recovery_required(&self) -> bool { self.paging_endpoint .as_ref() diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/dyno.rs b/core/continuum-serving/src/modules/serving_daemon/tests/dyno.rs index cff388f5e0..dba46f6ce2 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests/dyno.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests/dyno.rs @@ -226,7 +226,7 @@ mod the_pool_fits_the_host { assert_eq!(need, 478_382 + u64::from(crate::inference::planning::MIN_SERVE_CTX), "the grants' 1.25 over 382,706, plus the scratch sequence"); let fit = pool_fit(need, Some(&fp), host(room), CACHE_MIB * MIB, SEQUENCES, TRAINED); assert_eq!(fit, PoolFit::Fits { demand: need, fit: 566_990 }, "the room would hold 566,990: never filled"); - let pool = fit.pool(SEQUENCES); + let pool = fit.pool(SEQUENCES, crate::inference::planning::MIN_SERVE_CTX); assert_eq!(pool, 480_430); let freed = demand(&fp) - pool; assert_eq!(freed, 142_643); @@ -239,7 +239,7 @@ mod the_pool_fits_the_host { // The engine it replaces returns its measured anonymous bytes (24,969,922,712 B). let replacing = HostRoom::of(&HostMemoryReading { free_bytes: 32_000 * MIB, ..reading }, swap, 24_969_922_712); assert!(matches!(pool_fit(need, Some(&fp), host(replacing), CACHE_MIB * MIB, SEQUENCES, TRAINED), PoolFit::Fits { .. }), "a replaced engine's bytes come back"); - assert_eq!(pool_fit(need, Some(&fp), Rooms { host: None, device: None }, CACHE_MIB * MIB, SEQUENCES, TRAINED).pool(SEQUENCES), need, "no reading: never a dark node"); + assert_eq!(pool_fit(need, Some(&fp), Rooms { host: None, device: None }, CACHE_MIB * MIB, SEQUENCES, TRAINED).pool(SEQUENCES, crate::inference::planning::MIN_SERVE_CTX), need, "no reading: never a dark node"); } } diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index c561ea1fd9..54fb25a25c 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -11ad8be8d17feea19242471993e56f8f3ea0b91f +dccd6dbf976797859d19f188fd4fa4a9d7cd9c69 diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 11ad8be8d1..dccd6dbf97 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 11ad8be8d17feea19242471993e56f8f3ea0b91f +Subproject commit dccd6dbf976797859d19f188fd4fa4a9d7cd9c69 diff --git a/docs/architecture/CONTINUUM-ENGINE.md b/docs/architecture/CONTINUUM-ENGINE.md index 28a1a31bad..78dd4598c5 100644 --- a/docs/architecture/CONTINUUM-ENGINE.md +++ b/docs/architecture/CONTINUUM-ENGINE.md @@ -1314,6 +1314,11 @@ The fills themselves are by design, and one checkpoint at her stable end serves #### 4.7.3 The contract across the seam +- **At launch**, the seated minds supply demand and the backend declares its physical streams. + The native scheduler has one decoding stream and one staging stream. Serving charges the two + fixed stream costs before fitting KV into the host and device grants. It rounds each stream's + window down to native alignment within the fitted pool and the model's trained ceiling. + After launch, admission and prompt fitting use the geometry the running engine reports. - **Core to engine, per request:** her prompt's boundaries as token positions: the head end, the stable end (where her changing tail starts), and each activity's span. The request already carries `view_messages` spans for this. The engine keeps a checkpoint exactly at the stable end