From e084e38e93476bb3832f4ddc75bac9321fed1d00 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 16:20:58 -0600 Subject: [PATCH 01/41] Learn a deeper recurrent checkpoint after a short rewind --- .../src/inference/backends/persona_scheduler/driver.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) 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..969db9361d 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -640,8 +640,14 @@ impl Driver<'_, '_> { 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) { + // 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[0].is_some_and(|view| shared < view) { turn.boundaries[1] = Some(shared); } let (from, start) = match decided { From e730ea7ec5e589795e9d851403c4d3d2392da712 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 19:06:56 -0600 Subject: [PATCH 02/41] Estimate waiting prefill once per eligible turn --- .../backends/persona_scheduler/driver.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) 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 969db9361d..59de9a5fa4 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -373,7 +373,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. @@ -555,7 +556,7 @@ 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 }); + turns.push(Turn { req, id, one_off, prompt, basis, genes, sampler, phase: Phase::Waiting(Default::default()), submitted: Instant::now(), spent: Spent::default(), boundaries: [boundary, None], answer, cancel }); } Err(refused) => { tell(&req.response_tx, TokenEvent::Error(refused.to_string())); @@ -576,11 +577,11 @@ impl Driver<'_, '_> { .map(|&index| { let turn = &turns[index]; let (decoding, remaining) = match &turn.phase { - Phase::Waiting => { + 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)) - } + turn.prompt.len().saturating_sub(reused) + })), Phase::Prefilling { pos } => (false, turn.prompt.len().saturating_sub(*pos)), Phase::Decoding { .. } => (true, 0), }; @@ -603,7 +604,7 @@ 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); @@ -611,8 +612,8 @@ impl Driver<'_, '_> { turn.phase = Phase::Prefilling { pos: from }; } 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), }; From 9333856806c69f1c2c84036335dc8ef605a9d6f1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 19:58:58 -0600 Subject: [PATCH 03/41] Schedule overdue resident turns at landed frame boundaries --- .../backends/persona_scheduler/driver.rs | 54 +++++++++++++++---- .../backends/persona_scheduler/frame.rs | 41 +++++++------- .../backends/persona_scheduler/record.rs | 2 + 3 files changed, 67 insertions(+), 30 deletions(-) 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 59de9a5fa4..c7c5f399ce 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -90,6 +90,7 @@ type Parts = PersonaParts; enum Tenure { Resident, OneOff, + FinishedOneOff, } /// The tokens her blocks hold, and her checkpoint at her last view's end while what she holds still @@ -184,6 +185,8 @@ struct Driver<'c, 'm> { model_id: String, /// The stop has suspended every mind: no new turn is taken. stopping: bool, + bound_since: Instant, + prefill_sample: Option<(usize, std::time::Duration)>, } /// The root resume: every mind the last stop published, held Warm (in RAM, bound when scheduled), @@ -298,6 +301,8 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { store: store.ok(), model_id: config.model.clone(), stopping: false, + bound_since: Instant::now(), + prefill_sample: None, }; // 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 @@ -330,16 +335,18 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { while let Ok(submission) = requests.try_recv() { driver.take(submission, &mut turns); } - let Some(index) = driver.pick(&turns) else { continue }; - match driver.step(&mut turns[index]) { + let Some((index, ready)) = driver.pick(&turns) else { continue }; + match driver.step(&mut turns[index], ready) { Ok(Advanced::Continues) => {} Ok(Advanced::Done(done)) => { let turn = turns.remove(index); + driver.finish_one_off(&turn); driver.emit.send(emit::Out::End { answer: turn.answer, event: done }); } Err(refused) => { log.warn(&format!("turn refused: {refused}")); let turn = turns.remove(index); + driver.finish_one_off(&turn); driver.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error(refused.to_string()) }); } } @@ -390,6 +397,8 @@ struct Spent { start: &'static str, checkpoint_ms: u64, first_step: Option, + last_landed: Option, + longest_gap: std::time::Duration, switch: std::time::Duration, prefill: std::time::Duration, decode: std::time::Duration, @@ -568,7 +577,7 @@ impl Driver<'_, '_> { /// candidate; among candidates, `frame::pick` decides. A waiting turn's prefill is what she /// 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 { + fn pick(&mut self, turns: &[Turn]) -> Option<(usize, usize)> { 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(); @@ -585,22 +594,25 @@ impl Driver<'_, '_> { Phase::Prefilling { pos } => (false, turn.prompt.len().saturating_sub(*pos)), Phase::Decoding { .. } => (true, 0), }; - let waited_ms = record::whole_ms(turn.submitted.elapsed()); + let waited_ms = record::whole_ms(turn.spent.last_landed.unwrap_or(turn.submitted).elapsed()); frame::Candidate { active: active == Some(turn.id), decoding, remaining, waited_ms } }) .collect(); - frame::pick(&candidates).map(|chosen| eligible[chosen]) + frame::pick(&candidates, record::whole_ms(self.bound_since.elapsed())).map(|chosen| (eligible[chosen], eligible.len())) } /// 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 { + fn step(&mut self, turn: &mut Turn, ready: usize) -> Result { + let gap = turn.spent.last_landed.unwrap_or(turn.submitted).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()); } if self.engine.active() != Some(turn.id) { let switching = Instant::now(); self.switch_to(turn.id, turn.one_off)?; + self.bound_since = switching; turn.spent.switch += switching.elapsed(); turn.spent.switches += 1; } @@ -614,10 +626,11 @@ impl Driver<'_, '_> { let stepping = Instant::now(); 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::Prefilling { pos } => (self.prefill_chunk(turn, pos, ready).map(|()| Advanced::Continues), false), Phase::Decoding { token, pos, generated } => (self.decode_token(turn, token, pos, generated), true), }; let stepped = Instant::now(); + turn.spent.last_landed = Some(stepped); let took = stepped.saturating_duration_since(stepping); if decoding { turn.spent.decode += took; @@ -702,10 +715,17 @@ impl Driver<'_, '_> { /// One chunk of her prompt from `pos`. The last chunk asks for logits and samples her first /// 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> { + fn prefill_chunk(&mut self, turn: &mut Turn, pos: usize, ready: 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); + // A submission can arrive during this frame. Size the next native call from + // observed prefill time so a long prompt yields at the service boundary. + let started = Instant::now(); + let allowance = u128::from(frame::share_ms(ready)) * 1_000_000; + let count = self.prefill_sample.map_or(1, |(tokens, elapsed)| { + ((tokens as u128 * allowance) / elapsed.as_nanos().max(1)).clamp(1, self.batch.get() as u128) as usize + }); + let end = pos.saturating_add(count).min(limit); let chunk = turn.prompt[pos..end].to_vec(); let last = end == turn.prompt.len(); let from = i32::try_from(pos).map_err(|_| TurnError::TooLong)?; @@ -717,6 +737,7 @@ impl Driver<'_, '_> { if let Some(index) = turn.boundaries.iter().position(|boundary| *boundary == Some(end)) { self.keep_checkpoint(turn, index, end)?; } + self.prefill_sample = Some((len, started.elapsed())); turn.phase = Phase::Prefilling { pos: end }; return Ok(()); } @@ -725,6 +746,7 @@ impl Driver<'_, '_> { 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)?; + self.prefill_sample = Some((len, started.elapsed())); turn.phase = Phase::Decoding { token, pos, generated: 0 }; Ok(()) } @@ -784,6 +806,7 @@ impl Driver<'_, '_> { learned_boundary: turn.boundaries[1].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), @@ -830,10 +853,19 @@ impl Driver<'_, '_> { self.retire_previous() } - /// Park the mind whose retirement finishes. A one-off is dropped, and her blocks with her. + fn finish_one_off(&mut self, turn: &Turn) { + if turn.one_off { + self.parked.remove(&turn.id); + if let Some(mind) = self.engine.active_mut().filter(|mind| mind.id() == turn.id) { + mind.parts_mut().decode = Tenure::FinishedOneOff; + } + } + } + + /// 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 previous.parts().decode != Tenure::FinishedOneOff { self.parked.insert(previous.id(), previous); } Ok(()) 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..01d98e8c1a 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs @@ -3,16 +3,13 @@ //! 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). //! -//! 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 is this one pure function, so the owner of goal 9's scheduler replaces it here and -//! nowhere else. +//! Eligible turns share a one-second service budget. The bound mind advances until another +//! turn is due, then the oldest unserved turn gets the stream at the next landed frame. +const SERVICE_BUDGET_MS: u64 = 1000; + +pub(super) fn share_ms(ready: usize) -> u64 { + (SERVICE_BUDGET_MS / ready.max(1) as u64).max(1) +} /// A turn as the frame sees it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -23,7 +20,7 @@ pub(super) struct Candidate { pub decoding: 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, } @@ -36,8 +33,14 @@ impl Candidate { } /// The index of the turn the next frame advances, or `None` for no turns. -pub(super) fn pick(turns: &[Candidate]) -> Option { - if let Some(decoding) = turns.iter().position(|turn| turn.active && turn.decoding) { +pub(super) fn pick(turns: &[Candidate], bound_ms: u64) -> Option { + let share_ms = share_ms(turns.len()); + if let Some((index, other)) = turns.iter().enumerate().filter(|(_, t)| !t.active).max_by_key(|(_, t)| t.waited_ms) { + if other.waited_ms >= SERVICE_BUDGET_MS || (other.waited_ms >= share_ms && bound_ms >= share_ms) { + return Some(index); + } + } + if let Some(decoding) = turns.iter().position(|turn| turn.active && (turn.decoding || (bound_ms < share_ms && turns.iter().any(|other| other.decoding)))) { return Some(decoding); } turns @@ -60,18 +63,18 @@ mod tests { // 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); + fn a_short_tail_never_waits_behind_a_long_prompt_and_an_overdue_turn_can_preempt_decode() { + assert_eq!(pick(&[], 0), 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"); + assert_eq!(pick(&[long_active, short], 0), Some(1), "the short tail switches in at the chunk boundary"); 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], 500), Some(0), "an overdue turn interrupts an answer"); 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, 1_000, 0), aged], 0), 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"); + assert_eq!(pick(&[turn(false, false, 500, 0), turn(true, false, 500, 0)], 0), Some(1), "a tie keeps the bound mind"); } } 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..91e6c35fa3 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs @@ -57,6 +57,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, @@ -83,6 +84,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, From 4341d3ca995dc6eaba1310523ae491acca96a15d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 20:31:52 -0600 Subject: [PATCH 04/41] Represent resident readiness and service timing explicitly --- .../backends/persona_scheduler/driver.rs | 26 ++++++++++--------- .../backends/persona_scheduler/frame.rs | 7 ++--- 2 files changed, 18 insertions(+), 15 deletions(-) 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 c7c5f399ce..cc8a4fb1c5 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -366,6 +366,7 @@ 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. @@ -397,7 +398,6 @@ struct Spent { start: &'static str, checkpoint_ms: u64, first_step: Option, - last_landed: Option, longest_gap: std::time::Duration, switch: std::time::Duration, prefill: std::time::Duration, @@ -565,7 +565,8 @@ 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(Default::default()), submitted: Instant::now(), spent: Spent::default(), boundaries: [boundary, None], answer, cancel }); + let submitted = Instant::now(); + turns.push(Turn { req, id, one_off, prompt, basis, genes, sampler, phase: Phase::Waiting(Default::default()), submitted, ready_since: submitted, spent: Spent::default(), boundaries: [boundary, None], answer, cancel }); } Err(refused) => { tell(&req.response_tx, TokenEvent::Error(refused.to_string())); @@ -577,7 +578,7 @@ impl Driver<'_, '_> { /// candidate; among candidates, `frame::pick` decides. A waiting turn's prefill is what she /// 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<(usize, usize)> { + fn pick(&mut self, turns: &[Turn]) -> Option<(usize, std::num::NonZeroUsize)> { 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(); @@ -594,17 +595,18 @@ impl Driver<'_, '_> { Phase::Prefilling { pos } => (false, turn.prompt.len().saturating_sub(*pos)), Phase::Decoding { .. } => (true, 0), }; - let waited_ms = record::whole_ms(turn.spent.last_landed.unwrap_or(turn.submitted).elapsed()); + let waited_ms = record::whole_ms(turn.ready_since.elapsed()); frame::Candidate { active: active == Some(turn.id), decoding, remaining, waited_ms } }) .collect(); - frame::pick(&candidates, record::whole_ms(self.bound_since.elapsed())).map(|chosen| (eligible[chosen], eligible.len())) + let ready = std::num::NonZeroUsize::new(eligible.len())?; + frame::pick(&candidates, record::whole_ms(self.bound_since.elapsed())).map(|chosen| (eligible[chosen], ready)) } /// 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, ready: usize) -> Result { - let gap = turn.spent.last_landed.unwrap_or(turn.submitted).elapsed(); + fn step(&mut self, turn: &mut Turn, ready: std::num::NonZeroUsize) -> Result { + 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()); @@ -630,7 +632,7 @@ impl Driver<'_, '_> { Phase::Decoding { token, pos, generated } => (self.decode_token(turn, token, pos, generated), true), }; let stepped = Instant::now(); - turn.spent.last_landed = Some(stepped); + turn.ready_since = stepped; let took = stepped.saturating_duration_since(stepping); if decoding { turn.spent.decode += took; @@ -715,16 +717,16 @@ impl Driver<'_, '_> { /// One chunk of her prompt from `pos`. The last chunk asks for logits and samples her first /// 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, ready: usize) -> Result<(), TurnError> { + fn prefill_chunk(&mut self, turn: &mut Turn, pos: usize, ready: std::num::NonZeroUsize) -> 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 // A submission can arrive during this frame. Size the next native call from // observed prefill time so a long prompt yields at the service boundary. let started = Instant::now(); let allowance = u128::from(frame::share_ms(ready)) * 1_000_000; - let count = self.prefill_sample.map_or(1, |(tokens, elapsed)| { - ((tokens as u128 * allowance) / elapsed.as_nanos().max(1)).clamp(1, self.batch.get() as u128) as usize - }); + let count = self.prefill_sample.and_then(|(tokens, elapsed)| { + (tokens as u128 * allowance).checked_div(elapsed.as_nanos()) + }).map_or(1, |count| count.clamp(1, self.batch.get() as u128) as usize); let end = pos.saturating_add(count).min(limit); let chunk = turn.prompt[pos..end].to_vec(); let last = end == turn.prompt.len(); 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 01d98e8c1a..954a258e72 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs @@ -5,10 +5,11 @@ //! //! Eligible turns share a one-second service budget. The bound mind advances until another //! turn is due, then the oldest unserved turn gets the stream at the next landed frame. +// derived-or-floor: the conversational service requirement allows one second between eligible frames. const SERVICE_BUDGET_MS: u64 = 1000; -pub(super) fn share_ms(ready: usize) -> u64 { - (SERVICE_BUDGET_MS / ready.max(1) as u64).max(1) +pub(super) fn share_ms(ready: std::num::NonZeroUsize) -> u64 { + SERVICE_BUDGET_MS.div_ceil(ready.get() as u64) } /// A turn as the frame sees it. @@ -34,7 +35,7 @@ impl Candidate { /// The index of the turn the next frame advances, or `None` for no turns. pub(super) fn pick(turns: &[Candidate], bound_ms: u64) -> Option { - let share_ms = share_ms(turns.len()); + let share_ms = share_ms(std::num::NonZeroUsize::new(turns.len())?); if let Some((index, other)) = turns.iter().enumerate().filter(|(_, t)| !t.active).max_by_key(|(_, t)| t.waited_ms) { if other.waited_ms >= SERVICE_BUDGET_MS || (other.waited_ms >= share_ms && bound_ms >= share_ms) { return Some(index); From 082236b4cfb618d0cbe63f96989c932aaa273fc5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 21:23:07 -0600 Subject: [PATCH 05/41] Retain the earliest valid learned checkpoint across deeper captures --- .../inference/backends/persona_scheduler/driver.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) 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 cc8a4fb1c5..ba73b3aac2 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -98,7 +98,8 @@ enum Tenure { #[derive(Default)] struct History { held: Vec, - kept: [Option; 2], + /// 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 @@ -698,7 +699,16 @@ impl Driver<'_, '_> { /// 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> { let taking = Instant::now(); - let previous = self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens.kept[index].take(); + let history = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens; + // When a learned prefix grows, retain the older native snapshot for turns + // whose input changes earlier. History::cut invalidates every slot together. + let [_, latest, earliest] = &mut history.kept; + if index == 1 && latest.as_ref().is_some_and(|prior| { + prior.end < end && earliest.as_ref().is_none_or(|saved| prior.end < saved.end) + }) { + std::mem::swap(latest, earliest); + } + let previous = history.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 From 8dfd7861fa1be8800e060067e744136f13351ca3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 21:49:11 -0600 Subject: [PATCH 06/41] Keep native checkpoint custody in resident history --- .../backends/persona_scheduler/driver.rs | 111 +++--------- .../persona_scheduler/driver/history.rs | 168 ++++++++++++++++++ 2 files changed, 189 insertions(+), 90 deletions(-) create mode 100644 core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs 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 ba73b3aac2..2ee985c01a 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -93,37 +93,8 @@ enum Tenure { FinishedOneOff, } -/// 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, - /// 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()) - } -} +mod history; +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> { @@ -137,26 +108,6 @@ 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 { her.parts().tokens.reuse(&her.parts().genome, prompt, basis) @@ -216,7 +167,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::restored(mind.held), genome: Basis { genes: mind.basis }, learning: (), decode: Tenure::Resident }; parked.insert(id, Mind::new(id, epoch, parts)); } Err(refused) => { @@ -371,7 +322,7 @@ struct Turn { 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 @@ -533,7 +484,7 @@ impl Driver<'_, '_> { /// 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))?; @@ -567,7 +518,7 @@ impl Driver<'_, '_> { 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) }); let submitted = Instant::now(); - turns.push(Turn { req, id, one_off, prompt, basis, genes, sampler, phase: Phase::Waiting(Default::default()), submitted, ready_since: submitted, spent: Spent::default(), boundaries: [boundary, None], answer, cancel }); + 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 }); } Err(refused) => { tell(&req.response_tx, TokenEvent::Error(refused.to_string())); @@ -664,8 +615,8 @@ impl Driver<'_, '_> { reuse::Reuse::Restart(reuse::Miss::Diverged | reuse::Miss::NoCheckpoint) => shared > 0, _ => false, }; - if can_learn && her.parts().genome == basis && turn.boundaries[0].is_some_and(|view| shared < view) { - turn.boundaries[1] = Some(shared); + 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"), @@ -686,41 +637,21 @@ 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 history = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens; - // When a learned prefix grows, retain the older native snapshot for turns - // whose input changes earlier. History::cut invalidates every slot together. - let [_, latest, earliest] = &mut history.kept; - if index == 1 && latest.as_ref().is_some_and(|prior| { - prior.end < end && earliest.as_ref().is_none_or(|saved| prior.end < saved.end) - }) { - std::mem::swap(latest, earliest); - } - let previous = history.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 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, - } - })?; + let Some(mut blocks) = history.capture_buffer(kind, end) else { return Ok(()) }; + if self.engine.checkpoint_active(&mut blocks).is_ok_and(|pos| pos as usize + 1 == end) { + self.record(|her| her.tokens.save(kind, blocks, end, turn.basis.clone()))?; + } turn.spent.checkpoint_ms += record::whole_ms(taking.elapsed()); Ok(()) } @@ -729,7 +660,7 @@ 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, ready: std::num::NonZeroUsize) -> 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 limit = turn.boundaries.next_end(pos, turn.prompt.len()); // A submission can arrive during this frame. Size the next native call from // observed prefill time so a long prompt yields at the service boundary. let started = Instant::now(); @@ -746,8 +677,8 @@ impl Driver<'_, '_> { 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)?; + if let Some(kind) = turn.boundaries.at(end) { + self.keep_checkpoint(turn, kind, end)?; } self.prefill_sample = Some((len, started.elapsed())); turn.phase = Phase::Prefilling { pos: end }; @@ -814,8 +745,8 @@ impl Driver<'_, '_> { 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), 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..3c11e64c5a --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs @@ -0,0 +1,168 @@ +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::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, + }, + ) + } +} + +#[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 History { + pub(super) fn restored(held: Vec) -> Self { + Self { + held, + ..Self::default() + } + } + 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 }); + } +} +pub(super) struct Snapshot { + slot: usize, + checkpoint: KeptCheckpoint, +} +impl Snapshot { + pub(super) fn blocks(&self) -> &llama::PersonaCheckpoint { + &self.checkpoint.blocks + } +} From 9403533a2649e9f431aa4e0f742407de404d09ca Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 22:19:04 -0600 Subject: [PATCH 07/41] Express history transfer and checkpoint basis ownership --- .../backends/persona_scheduler/driver.rs | 4 ++-- .../backends/persona_scheduler/driver/history.rs | 15 +++++++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) 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 2ee985c01a..3c4697d40b 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -167,7 +167,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::restored(mind.held), 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) => { @@ -650,7 +650,7 @@ impl Driver<'_, '_> { let history = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens; let Some(mut blocks) = history.capture_buffer(kind, end) else { return Ok(()) }; if self.engine.checkpoint_active(&mut blocks).is_ok_and(|pos| pos as usize + 1 == end) { - self.record(|her| her.tokens.save(kind, blocks, end, turn.basis.clone()))?; + self.record(|her| her.tokens.save(kind, blocks, end, &turn.basis))?; } turn.spent.checkpoint_ms += record::whole_ms(taking.elapsed()); Ok(()) 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 index 3c11e64c5a..e36673d3fc 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs @@ -98,13 +98,16 @@ impl Boundaries { .find_map(|(kind, pos)| (pos == end).then_some(kind)) } } -impl History { - pub(super) fn restored(held: Vec) -> Self { +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() } @@ -152,9 +155,13 @@ impl History { kind: Boundary, blocks: llama::PersonaCheckpoint, end: usize, - basis: Basis, + basis: &Basis, ) { - *self.slot(kind) = Some(KeptCheckpoint { blocks, end, basis }); + *self.slot(kind) = Some(KeptCheckpoint { + blocks, + end, + basis: basis.clone(), + }); } } pub(super) struct Snapshot { From b9b60cbac7ca22ec538a4b977ca785cd3f7a15f0 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 19 Nov 2026 22:51:01 -0600 Subject: [PATCH 08/41] Compare token history once when binding a resident --- .../backends/persona_scheduler/driver.rs | 9 ++-- .../persona_scheduler/driver/history.rs | 2 +- .../backends/persona_scheduler/reuse.rs | 51 ++++++++++--------- core/continuum-persona-engine/src/turn.rs | 26 ++++++++-- 4 files changed, 54 insertions(+), 34 deletions(-) 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 3c4697d40b..0bc9a0fae4 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -109,7 +109,7 @@ impl Footprint for Bound<'_, '_, '_> { } /// 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) } @@ -541,7 +541,7 @@ impl Driver<'_, '_> { let (decoding, 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 + 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 } => (false, turn.prompt.len().saturating_sub(*pos)), @@ -605,9 +605,8 @@ 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; + 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 { 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 index e36673d3fc..a717d295fd 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs @@ -48,7 +48,7 @@ impl History { /// 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::Reuse { + 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, 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-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) } } From 65534329a798944faa41c6f5679420738c9503a9 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 01:23:16 -0600 Subject: [PATCH 09/41] Correlate empty native turns with their requested tool catalog --- .../src/inference/llamacpp_adapter/chat_turn.rs | 12 +++++++++++- .../src/inference/llamacpp_adapter/provider.rs | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) 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..27b0ec3097 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs @@ -157,14 +157,24 @@ 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, written: &str, tokens: usize, end: GenerationEnd, stops: &[String], request: &TextGenerationRequest) { 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().unwrap_or_default().iter() + .chain(request.tail_tools.as_deref().unwrap_or_default()).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..2d90af3037 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs @@ -511,7 +511,7 @@ 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); + turn.probe_if_empty(&written, tokens, end, &stop_owned, &request); (turn.text, turn.reasoning, turn.tool_calls) } Err(refused) => return Err(refused.to_string()), From 82a5cad0da005fad9d7cee3f4f345e54a599597c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 02:00:55 -0600 Subject: [PATCH 10/41] Group native generation output in the empty-turn probe --- .../src/inference/llamacpp_adapter/chat_turn.rs | 15 ++++++++++++--- .../src/inference/llamacpp_adapter/provider.rs | 3 ++- 2 files changed, 14 insertions(+), 4 deletions(-) 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 27b0ec3097..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,11 +153,20 @@ 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], request: &TextGenerationRequest) { + 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; } @@ -166,8 +175,8 @@ impl ParsedTurn { 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().unwrap_or_default().iter() - .chain(request.tail_tools.as_deref().unwrap_or_default()).any(|tool| tool.name == name)); + 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!( diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs index 2d90af3037..5b4b9bf935 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs @@ -511,7 +511,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, &request); + 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()), From ad2075c70a685baae5b9a9501f6e865694d591fa Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 02:23:06 -0600 Subject: [PATCH 11/41] Pin the deployed Qwen argument-order parser --- core/vendor/LLAMA_CPP_PIN | 2 +- core/vendor/llama.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 From 1af6ffde92c9275a9dfcca54e420a712b9f00805 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 02:44:10 -0600 Subject: [PATCH 12/41] Retain one-off native state only while its turn owns it --- .../inference/backends/persona_scheduler/driver.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) 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 0bc9a0fae4..2526a84f84 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}; @@ -90,7 +90,6 @@ type Parts = PersonaParts; enum Tenure { Resident, OneOff, - FinishedOneOff, } mod history; @@ -123,6 +122,8 @@ struct Driver<'c, 'm> { batch: NonZeroUsize, 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 @@ -247,6 +248,7 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { batch, engine: PersonaEngine::new(tier), parked, + live_one_offs: HashSet::new(), emit: Outbox::new(emit), record: Outbox::new(record), answers: 0, @@ -445,6 +447,7 @@ impl Driver<'_, '_> { fn suspend(&mut self, turns: &mut Vec) -> Suspended { self.stopping = true; for turn in turns.drain(..) { + self.finish_one_off(&turn); self.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error("the engine is stopping: her state is preserved".into()) }); } let Some(mut store) = self.store.take() else { @@ -518,6 +521,7 @@ impl Driver<'_, '_> { 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) }); let submitted = Instant::now(); + if one_off { self.live_one_offs.insert(id); } 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 }); } Err(refused) => { @@ -798,16 +802,14 @@ impl Driver<'_, '_> { fn finish_one_off(&mut self, turn: &Turn) { if turn.one_off { self.parked.remove(&turn.id); - if let Some(mind) = self.engine.active_mut().filter(|mind| mind.id() == turn.id) { - mind.parts_mut().decode = Tenure::FinishedOneOff; - } + 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 previous.parts().decode != Tenure::FinishedOneOff { + if resident(&previous) || self.live_one_offs.contains(&previous.id()) { self.parked.insert(previous.id(), previous); } Ok(()) From 3a59d95eb9cd4bfd549db47ea0ae7d154fc36354 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 03:06:37 -0600 Subject: [PATCH 13/41] Resolve retiring native state before recording suspend inventory --- .../src/inference/backends/persona_scheduler/driver.rs | 7 +++++++ 1 file changed, 7 insertions(+) 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 2526a84f84..6a18573452 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -450,6 +450,13 @@ impl Driver<'_, '_> { self.finish_one_off(&turn); self.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error("the engine is stopping: her state is preserved".into()) }); } + // A refused copy-out still owns native state outside the parked inventory. Finish it + // before enumerating minds, or leave the store and last complete generation in custody. + if let Some(id) = self.engine.retiring() { + if let Err(why) = self.retire_previous() { + return Suspended { preserved: 0, retained: vec![(id.0, why.to_string())] }; + } + } 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())] }; }; From 6404cf3b158b42a2ec13a7b3d216784c3c814b5b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 03:45:39 -0600 Subject: [PATCH 14/41] Report every resident held when suspend cannot preserve the node --- .../backends/persona_scheduler/driver.rs | 20 +++++++++++-------- core/continuum-persona-engine/src/engine.rs | 5 +++++ .../src/engine/tests.rs | 2 ++ .../src/pipeline/roles.rs | 17 +++++++++++----- 4 files changed, 31 insertions(+), 13 deletions(-) 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 6a18573452..88a43e9c8e 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -450,20 +450,24 @@ impl Driver<'_, '_> { self.finish_one_off(&turn); self.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error("the engine is stopping: her state is preserved".into()) }); } - // A refused copy-out still owns native state outside the parked inventory. Finish it - // before enumerating minds, or leave the store and last complete generation in custody. + 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() + }; + Suspended { preserved: 0, retained } + }; if let Some(id) = self.engine.retiring() { if let Err(why) = self.retire_previous() { - return Suspended { preserved: 0, retained: vec![(id.0, why.to_string())] }; + 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(); 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 From 115426f15be61d8d903627ac2fbaa357480c0e3f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 08:28:21 -0600 Subject: [PATCH 15/41] Give the requesting task ownership of its submitted inference turn --- .../backends/llamacpp/llama_cpp_backend.rs | 82 ++++++------------- .../backends/persona_scheduler/driver.rs | 5 ++ .../inference/llamacpp_adapter/provider.rs | 12 +-- 3 files changed, 38 insertions(+), 61 deletions(-) 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..4d0dd8950c 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 @@ -518,11 +518,7 @@ impl LlamaCppBackend { 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( + futures::executor::block_on(self.submit_for_persona( allocation, None, TurnPrompt { text: prompt, stable_prefix: None }, @@ -530,19 +526,11 @@ impl LlamaCppBackend { sampling, stop_sequences, active_loras, - ) + )?.collect()) } - /// 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(crate) fn submit_for_persona( &self, allocation: GenerationAllocation, persona_id: Option, @@ -551,14 +539,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 @@ -611,40 +598,23 @@ impl LlamaCppBackend { return Err(refused.to_string()); } - // 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(); + Ok(TurnAnswer { events: response_rx, started: gen_start, prompt_chars: prompt_len_chars, stops: stop_sequences.iter().map(|s| s.to_string()).collect() }) + } +} +/// Dropping a turn drops its receiver even when the native driver is busy. +pub(crate) struct TurnAnswer { + events: tokio::sync::mpsc::UnboundedReceiver, + started: Instant, + prompt_chars: usize, + stops: Vec, +} + +impl TurnAnswer { + pub(crate) 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 +625,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/driver.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs index 88a43e9c8e..aef0611c70 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -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 @@ -573,6 +575,9 @@ 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, ready: std::num::NonZeroUsize) -> 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() { diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs index 5b4b9bf935..acae1954ea 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs @@ -411,7 +411,8 @@ 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 || { let stop_refs: Vec<&str> = stop_for_closure.iter().map(|s| s.as_str()).collect(); // Page in each requested gene (idempotent) before generation. @@ -424,17 +425,18 @@ impl AIProviderAdapter for LlamaCppAdapter { .iter() .map(|(id, _, scale)| (id.clone(), *scale)) .collect(); - backend_for_blocking.generate_for_persona( - allocation, persona_id, + 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() }, 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 From c2ee2b9367c52edbad97cc7e0d3096f508f66255 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 08:58:41 -0600 Subject: [PATCH 16/41] Remove blocking generation wrapper from the native backend --- .../backends/llamacpp/llama_cpp_backend.rs | 31 +------------------ 1 file changed, 1 insertion(+), 30 deletions(-) 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 4d0dd8950c..6c68683ca9 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 @@ -325,7 +325,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,35 +500,6 @@ 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> { - futures::executor::block_on(self.submit_for_persona( - allocation, - None, - TurnPrompt { text: prompt, stable_prefix: None }, - max_tokens, - sampling, - stop_sequences, - active_loras, - )?.collect()) - } - /// Prepare and enqueue on a blocking worker. The caller owns the returned event receiver. pub(crate) fn submit_for_persona( &self, From db3cbff857e56f085ed5771db90f00b05c0232c5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 09:18:23 -0600 Subject: [PATCH 17/41] Enqueue flow work on submission and trace native worker parking --- .../tests/llamacpp_metal_throughput.rs | 23 ++++++++---- .../tests/qwen35_chat_pipeline_full.rs | 27 +++++++++----- .../src/inference/backends/llamacpp.rs | 2 +- .../backends/llamacpp/llama_cpp_backend.rs | 6 ++-- .../backends/persona_scheduler/driver.rs | 27 ++++++++++++-- core/continuum-flow/src/flow.rs | 36 +++++++++++-------- core/continuum-flow/src/tests.rs | 16 +++------ 7 files changed, 90 insertions(+), 47 deletions(-) diff --git a/core/continuum-core/tests/llamacpp_metal_throughput.rs b/core/continuum-core/tests/llamacpp_metal_throughput.rs index d999263993..fa7066a8b4 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 }, 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 }, 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..3e75cfb606 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 }, 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 }, 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 6c68683ca9..e7ef9e11d3 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 @@ -501,7 +501,7 @@ impl LlamaCppBackend { } /// Prepare and enqueue on a blocking worker. The caller owns the returned event receiver. - pub(crate) fn submit_for_persona( + pub fn submit_for_persona( &self, allocation: GenerationAllocation, persona_id: Option, @@ -574,7 +574,7 @@ impl LlamaCppBackend { } /// Dropping a turn drops its receiver even when the native driver is busy. -pub(crate) struct TurnAnswer { +pub struct TurnAnswer { events: tokio::sync::mpsc::UnboundedReceiver, started: Instant, prompt_chars: usize, @@ -582,7 +582,7 @@ pub(crate) struct TurnAnswer { } impl TurnAnswer { - pub(crate) async fn collect(mut self) -> Result<(String, usize), String> { + pub async fn collect(mut self) -> Result<(String, usize), String> { let mut output = String::new(); loop { match self.events.recv().await { 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 aef0611c70..94f7709744 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -273,6 +273,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; @@ -280,6 +283,24 @@ 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. @@ -415,10 +436,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. 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/tests.rs b/core/continuum-flow/src/tests.rs index f06ec703a9..7918214a90 100644 --- a/core/continuum-flow/src/tests.rs +++ b/core/continuum-flow/src/tests.rs @@ -125,17 +125,11 @@ fn a_full_background_queue_sheds_its_oldest_and_never_sheds_work() { async fn a_superseded_submission_resolves_at_once_with_its_reason() { let flow: Flow<&'static str> = 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 From 70850aaf7aecf614345ad024cfd874bb7ffceb40 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 09:44:18 -0600 Subject: [PATCH 18/41] Skip candidate ranking when only one turn can run --- .../src/inference/backends/persona_scheduler/driver.rs | 5 +++++ 1 file changed, 5 insertions(+) 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 94f7709744..9604a1d743 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -569,6 +569,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<(usize, std::num::NonZeroUsize)> { + // 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, std::num::NonZeroUsize::MIN)); + } 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(); From 6d6436db6d2b92f892a22f505f4c85331789751b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 09:49:48 -0600 Subject: [PATCH 19/41] Wake one shared stage when a resident phenotype changes --- Cargo.lock | 1 + core/continuum-genome/Cargo.toml | 1 + core/continuum-genome/src/genome/composer.rs | 2 +- .../src/genome/gene_residency.rs | 27 +------------- .../src/genome/gene_residency/reconcile.rs | 37 +++++++++++++++++++ 5 files changed, 42 insertions(+), 26 deletions(-) create mode 100644 core/continuum-genome/src/genome/gene_residency/reconcile.rs diff --git a/Cargo.lock b/Cargo.lock index d89523dfc7..8c0667d62d 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", 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/composer.rs b/core/continuum-genome/src/genome/composer.rs index b6d5850d04..e554e0d042 100644 --- a/core/continuum-genome/src/genome/composer.rs +++ b/core/continuum-genome/src/genome/composer.rs @@ -282,7 +282,7 @@ pub async fn compose(persona: Uuid, perception: &str) -> Option { let selection = select(need.as_ref(), &candidates, candidates.len(), &previous); probe_selection(persona, &selection, pending); residency.record_turn(persona, &selection.phenotype, now_ms); - residency.schedule_reconcile(); + residency.request_reconcile(); Some(selection.phenotype) } 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..240f75258d --- /dev/null +++ b/core/continuum-genome/src/genome/gene_residency/reconcile.rs @@ -0,0 +1,37 @@ +//! 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 std::sync::{Arc, OnceLock, Weak}; + +#[derive(Default)] +pub(super) struct Worker(OnceLock<(StageInput<()>, 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(in crate::genome) fn request_reconcile(self: &Arc) { + let (input, _) = self.reconcile_worker.0.get_or_init(|| { + spawn_stage(Reconcile(Arc::downgrade(self)), Capacity::latest()) + }); + match input.push(()) { + Ok(_) | Err(PushError::Full(())) => {} + Err(PushError::Stopped(())) => continuum_base::probe!( + class = "genome.page.worker_stopped", + "gene residency worker stopped before it could read the new phenotype" + ), + } + } +} From 785b7483545da67e92b363be5e1df0e1278de912 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 10:18:43 -0600 Subject: [PATCH 20/41] Close cancelled stage intake and rearm residency on its next wake --- core/continuum-flow/src/stage.rs | 3 +- core/continuum-flow/src/tests.rs | 18 +++++++++ .../src/genome/gene_residency/reconcile.rs | 38 +++++++++++++------ 3 files changed, 47 insertions(+), 12 deletions(-) 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, StageWorker<()>)>); +pub(super) struct Worker(Mutex>); + +struct Running { + input: StageInput<()>, + _worker: StageWorker<()>, +} struct Reconcile(Weak); @@ -23,15 +29,25 @@ impl Stage for Reconcile { impl GeneResidency { pub(in crate::genome) fn request_reconcile(self: &Arc) { - let (input, _) = self.reconcile_worker.0.get_or_init(|| { - spawn_stage(Reconcile(Arc::downgrade(self)), Capacity::latest()) - }); - match input.push(()) { - Ok(_) | Err(PushError::Full(())) => {} - Err(PushError::Stopped(())) => continuum_base::probe!( - class = "genome.page.worker_stopped", - "gene residency worker stopped before it could read the new phenotype" - ), + 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 }); } } From 9344d7659766769886a7c49002dceb563440a309 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 10:38:58 -0600 Subject: [PATCH 21/41] Preserve the gene residency scheduling contract for existing callers --- core/continuum-genome/src/genome/composer.rs | 2 +- core/continuum-genome/src/genome/gene_residency/reconcile.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/continuum-genome/src/genome/composer.rs b/core/continuum-genome/src/genome/composer.rs index e554e0d042..b6d5850d04 100644 --- a/core/continuum-genome/src/genome/composer.rs +++ b/core/continuum-genome/src/genome/composer.rs @@ -282,7 +282,7 @@ pub async fn compose(persona: Uuid, perception: &str) -> Option { let selection = select(need.as_ref(), &candidates, candidates.len(), &previous); probe_selection(persona, &selection, pending); residency.record_turn(persona, &selection.phenotype, now_ms); - residency.request_reconcile(); + residency.schedule_reconcile(); Some(selection.phenotype) } diff --git a/core/continuum-genome/src/genome/gene_residency/reconcile.rs b/core/continuum-genome/src/genome/gene_residency/reconcile.rs index 05b2ddc271..3daabc6738 100644 --- a/core/continuum-genome/src/genome/gene_residency/reconcile.rs +++ b/core/continuum-genome/src/genome/gene_residency/reconcile.rs @@ -28,7 +28,7 @@ impl Stage for Reconcile { } impl GeneResidency { - pub(in crate::genome) fn request_reconcile(self: &Arc) { + 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(()) { From c8b61e1c60c2340493049904506aa0ed6cad7b6f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 10:59:49 -0600 Subject: [PATCH 22/41] Surface native checkpoint capture and rewind outcomes --- .../backends/persona_scheduler/driver.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) 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 9604a1d743..217ffadd59 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -667,7 +667,11 @@ impl Driver<'_, '_> { 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", 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()), }; @@ -694,8 +698,14 @@ impl Driver<'_, '_> { let taking = Instant::now(); let history = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens; let Some(mut blocks) = history.capture_buffer(kind, end) else { return Ok(()) }; - if self.engine.checkpoint_active(&mut blocks).is_ok_and(|pos| pos as usize + 1 == end) { - self.record(|her| her.tokens.save(kind, blocks, end, &turn.basis))?; + 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", + expected_end = end as u64, native_position = i64::from(pos), "discarded misaligned native checkpoint"), + Err(error) => continuum_base::probe!(class = "persona.engine.checkpoint_failed", + expected_end = end as u64, error = %error, "native checkpoint capture failed"), } turn.spent.checkpoint_ms += record::whole_ms(taking.elapsed()); Ok(()) From 630955ad28e239ae5637560926cb2118b6aed6cf Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 11:29:38 -0600 Subject: [PATCH 23/41] Attribute checkpoint allocation and capture failures to the resident --- .../inference/backends/persona_scheduler/driver.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) 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 217ffadd59..704f4bdada 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -668,7 +668,7 @@ impl Driver<'_, '_> { reuse::Reuse::Rewind { from } => match self.rewind_to_checkpoint(from) { Ok(()) => (from, "rewind"), Err(error) => { - continuum_base::probe!(class = "persona.engine.rewind_failed", checkpoint_end = from as u64, + 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") } @@ -697,14 +697,19 @@ impl Driver<'_, '_> { fn keep_checkpoint(&mut self, turn: &mut Turn, kind: Boundary, end: usize) -> Result<(), TurnError> { let taking = Instant::now(); let history = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens; - let Some(mut blocks) = history.capture_buffer(kind, end) else { return Ok(()) }; + 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(()); + }; 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", + 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", + 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()); From 07ceb73cfb44e0e807f5dc1b268fc460ddd6d75e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 11:49:09 -0600 Subject: [PATCH 24/41] Borrow each prefill slice until submission and history update --- .../src/inference/backends/persona_scheduler/driver.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 704f4bdada..b75f035490 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -729,14 +729,14 @@ impl Driver<'_, '_> { (tokens as u128 * allowance).checked_div(elapsed.as_nanos()) }).map_or(1, |count| count.clamp(1, self.batch.get() as u128) as usize); let end = pos.saturating_add(count).min(limit); - let chunk = turn.prompt[pos..end].to_vec(); + 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))?; + self.record(|her| her.tokens.held.extend_from_slice(chunk))?; if let Some(kind) = turn.boundaries.at(end) { self.keep_checkpoint(turn, kind, end)?; } @@ -746,7 +746,7 @@ impl Driver<'_, '_> { } 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)?; self.prefill_sample = Some((len, started.elapsed())); From d3f24526abc2bc8c488aca5bd04ad5d14ec5dfbd Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 21:39:55 -0600 Subject: [PATCH 25/41] A turn's path from entry to the engine reports every transition it reaches, keyed by its request id The M5, 2026-11-21: Aris entered generate_text at 00:48:32 and was dropped 1,499 s later with no record of whether the engine ever held her turn; the driver logged nothing at admission, so the stall could not be placed (and was first misattributed to the grants). Now each transition is recorded once, keyed by the submitted request's id (`RequestId`, the adapter request_id, the one id crossing from her deliberation into the engine): - inference.generate.enter: gains `request`. - inference.generate.worker_started: the blocking worker began (a full pool delays this). - inference.generate.genes_ready: her genes are loaded (a gene load delays this). - persona.engine.enqueued: handed to the scheduler (prompt tokens, time since submit began). - persona.engine.admitted: the driver took it into its queue (queue depth, prompt tokens, ms since it was handed over: the driver's own latency to take requests). - persona.engine.first_frame: its first frame (ms since admission, reused tokens now known, prompt tokens, whether reaching her took a switch). - persona.generation.dropped: gains `request`, so a drop names the last transition it reached. The driver's two facts go through its record stage (one flow event each), not inline on the driver thread. Unknown stays unknown: a request sent with no id logs None. Checks (exit statuses captured from cargo, not a pipeline): cargo check -p continuum-engine -p continuum-cognition --tests: 0, no warnings in touched files; persona_scheduler tests 11 pass; cognition settle + generation_drop tests 23 pass; ratchets vs origin/codex/frame-prefill-estimate: 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/act_observe/settle/tests.rs | 6 +- .../src/cognition/generation_drop.rs | 5 ++ .../llm_deliberation_faculty/request.rs | 2 + .../backends/llamacpp/llama_cpp_backend.rs | 13 ++++ .../inference/backends/persona_scheduler.rs | 24 +++++++ .../backends/persona_scheduler/driver.rs | 25 +++++++- .../backends/persona_scheduler/record.rs | 3 + .../backends/persona_scheduler/transition.rs | 64 +++++++++++++++++++ .../inference/llamacpp_adapter/provider.rs | 19 +++++- 9 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs 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-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs b/core/continuum-engine/src/inference/backends/llamacpp/llama_cpp_backend.rs index e7ef9e11d3..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)] @@ -554,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, @@ -563,11 +566,21 @@ 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() }) } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index 4055c9d435..b1bea7c5c5 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -25,9 +25,28 @@ mod frame; mod reuse; mod geometry; mod sampling; +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)) + } +} + +impl std::fmt::Display for RequestId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + use std::sync::Arc; use llama::{KvCacheType, LoraAdapter, Model}; @@ -81,6 +100,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' 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 b75f035490..89e0e7f916 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -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::{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; @@ -369,6 +369,8 @@ enum Phase { /// Where a turn's time went, for its one probe row. #[derive(Default)] struct Spent { + /// Her first frame has been reported (`transition::At::FirstFrame`), so it is reported once. + framed: bool, reused: usize, shared_prefix_tokens: usize, /// How her prefill started: append, rewind, or the restart's reason. @@ -556,7 +558,14 @@ impl Driver<'_, '_> { self.emit.send(emit::Out::Open { answer, sink: req.response_tx.clone(), stops: req.stop_sequences.clone().into(), cancel: Arc::clone(&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())); @@ -622,6 +631,20 @@ impl Driver<'_, '_> { return Err(TurnError::NothingDecoded); } turn.phase = Phase::Prefilling { pos: from }; + if !turn.spent.framed { + turn.spent.framed = true; + self.record.send(record::Fact::Transition(transition::Transition { + request: turn.req.request.clone(), + persona: turn.id.0, + one_off: turn.one_off, + at: transition::At::FirstFrame { + waited_ms: record::whole_ms(turn.submitted.elapsed()), + reused_tokens: from, + prompt_tokens: turn.prompt.len(), + switched: turn.spent.switches > 0, + }, + })); + } } let stepping = Instant::now(); let (advanced, decoding) = match std::mem::replace(&mut turn.phase, Phase::Waiting(Default::default())) { 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 91e6c35fa3..223332e976 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs @@ -40,6 +40,8 @@ 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 reached a transition (admitted, first frame). + Transition(super::transition::Transition), /// A turn ended. Turn(TurnRow), } @@ -161,6 +163,7 @@ 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(), Fact::Turn(row) => { row.write(); self.close_window(self.last_end); 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..a1c4e3439e --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs @@ -0,0 +1,64 @@ +//! A turn's transitions inside the engine, each recorded once: admitted to the driver's queue, and +//! its first frame. Keyed by the submitted request's id, so a stall reads as the last transition it +//! reached (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 submitted to the scheduler. + since_submit_ms: u64, + }, + /// Her turn advanced for the first time. + FirstFrame { + /// Since the driver admitted her turn. + waited_ms: u64, + /// Prompt tokens her blocks already held: known once she is bound. + reused_tokens: usize, + prompt_tokens: usize, + /// Whether reaching her took a switch from another mind. + switched: bool, + }, +} + +/// 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 { + pub(super) fn write(self) { + match self.at { + At::Admitted { queue_depth, prompt_tokens, since_submit_ms } => continuum_base::probe!( + class = "persona.engine.admitted", + request = ?self.request, + 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::FirstFrame { waited_ms, reused_tokens, prompt_tokens, switched } => continuum_base::probe!( + class = "persona.engine.first_frame", + request = ?self.request, + persona = %self.persona, + one_off = self.one_off, + waited_ms = waited_ms, + reused_tokens = reused_tokens, + prompt_tokens = prompt_tokens, + switched = switched, + "a turn advanced for the first time" + ), + } + } +} diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs index acae1954ea..cf0a1a5793 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs @@ -237,6 +237,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, msg_count = request.messages.len(), max_tokens = ?request.max_tokens, has_system_prompt = request.system_prompt.is_some(), @@ -380,6 +381,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 — @@ -413,6 +415,14 @@ impl AIProviderAdapter for LlamaCppAdapter { "inference.forward.text", 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 = ?gen_start.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. @@ -421,13 +431,20 @@ 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 = ?gen_start.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.submit_for_persona( allocation, persona_id, - crate::inference::backends::llamacpp::TurnPrompt { text: &prompt_for_blocking, stable_prefix: stable_for_blocking.as_deref() }, + 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, From 56913f640b0629db1321900cc02d08104b0bf3f6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 22:10:26 -0600 Subject: [PATCH 26/41] Transitions per Codex's review of d3f24526ab: one entry origin, frame start apart from first progress, one key shape, the engine incarnation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - since_enter is measured from an instant taken at the top of generate_text (it was gen_start, started later, so it hid every step between entry and generation). - first_frame was emitted before the first chunk ran, so a blocked or failed chunk still read as advancement. Now frame_started (bound, prefill start known) and first_progress (the first step that succeeded natively, once, with its duration and whether it was prefill) are separate; Milestones (Admitted -> Started -> Progressed, an enum, not flags) decides each once, with a validator: a failed first step starts without progress; a multi-chunk turn reports progress once. - The request key logs as Some("…") at every site (the driver read Some(RequestId("…"))), so the adapter and driver ends join exactly; RequestId::as_str, and its unused Display deleted. - Every engine transition carries the incarnation of the engine that served it (the record stage already owns it), so a stale binding shows. - One Driver::transition replaces the hand-built transition at each site. check 0; persona_scheduler tests 12 pass (the milestone validator added); ratchets vs origin/codex/frame-prefill-estimate 0 (state_as_flags caught Milestones as two bools: now an enum). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../inference/backends/persona_scheduler.rs | 8 +- .../backends/persona_scheduler/driver.rs | 30 ++--- .../backends/persona_scheduler/record.rs | 2 +- .../backends/persona_scheduler/transition.rs | 106 +++++++++++++++--- .../inference/llamacpp_adapter/provider.rs | 8 +- 5 files changed, 116 insertions(+), 38 deletions(-) diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index b1bea7c5c5..946818b5a1 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -39,14 +39,14 @@ impl RequestId { pub fn new(id: &str) -> Self { Self(Arc::from(id)) } -} -impl std::fmt::Display for RequestId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.0) + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 } } + use std::sync::Arc; use llama::{KvCacheType, LoraAdapter, Model}; 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 89e0e7f916..de4ddca6aa 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -369,8 +369,8 @@ enum Phase { /// Where a turn's time went, for its one probe row. #[derive(Default)] struct Spent { - /// Her first frame has been reported (`transition::At::FirstFrame`), so it is reported once. - framed: bool, + /// 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. @@ -631,19 +631,10 @@ impl Driver<'_, '_> { return Err(TurnError::NothingDecoded); } turn.phase = Phase::Prefilling { pos: from }; - if !turn.spent.framed { - turn.spent.framed = true; - self.record.send(record::Fact::Transition(transition::Transition { - request: turn.req.request.clone(), - persona: turn.id.0, - one_off: turn.one_off, - at: transition::At::FirstFrame { - waited_ms: record::whole_ms(turn.submitted.elapsed()), - reused_tokens: from, - prompt_tokens: turn.prompt.len(), - switched: turn.spent.switches > 0, - }, - })); + 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(); @@ -661,6 +652,10 @@ impl Driver<'_, '_> { turn.spent.prefill += took; } self.record.send(record::Fact::Busy { started: stepping, ended: stepped }); + 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(TokenEvent::Done { tokens_generated, .. })) = &advanced { self.report_footprint(turn.id, turn.one_off); self.record.send(record::Fact::Turn(Self::row(turn, *tokens_generated))); @@ -879,6 +874,11 @@ impl Driver<'_, '_> { self.retire_previous() } + /// 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); 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 223332e976..2c5f91b6ed 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs @@ -163,7 +163,7 @@ 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(), + Fact::Transition(transition) => transition.write(self.incarnation), Fact::Turn(row) => { row.write(); self.close_window(self.last_end); diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs index a1c4e3439e..95587cba0c 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs @@ -1,6 +1,7 @@ -//! A turn's transitions inside the engine, each recorded once: admitted to the driver's queue, and -//! its first frame. Keyed by the submitted request's id, so a stall reads as the last transition it -//! reached (the M5, 2026-11-21: Aris entered `generate_text` at 00:48:32 and dropped 1,499 s later +//! 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; @@ -12,19 +13,58 @@ pub(super) enum At { /// Turns in the queue, hers included. queue_depth: usize, prompt_tokens: usize, - /// Since her turn was submitted to the scheduler. + /// Since her turn was handed to the scheduler. since_submit_ms: u64, }, - /// Her turn advanced for the first time. - FirstFrame { + /// 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. - waited_ms: u64, - /// Prompt tokens her blocks already held: known once she is bound. + 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 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. @@ -36,11 +76,15 @@ pub(super) struct Transition { } impl Transition { - pub(super) fn write(self) { + /// 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 = ?self.request, + request = ?request, + incarnation = incarnation, persona = %self.persona, one_off = self.one_off, queue_depth = queue_depth, @@ -48,17 +92,49 @@ impl Transition { since_submit_ms = since_submit_ms, "the driver took a turn into its queue" ), - At::FirstFrame { waited_ms, reused_tokens, prompt_tokens, switched } => continuum_base::probe!( - class = "persona.engine.first_frame", - request = ?self.request, + 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, - waited_ms = waited_ms, + since_admit_ms = since_admit_ms, reused_tokens = reused_tokens, prompt_tokens = prompt_tokens, switched = switched, - "a turn advanced for the first time" + "a turn's first frame began" + ), + 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/llamacpp_adapter/provider.rs b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs index cf0a1a5793..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,7 +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, + request = ?request.request_id.as_deref(), msg_count = request.messages.len(), max_tokens = ?request.max_tokens, has_system_prompt = request.system_prompt.is_some(), @@ -420,7 +422,7 @@ impl AIProviderAdapter for LlamaCppAdapter { continuum_base::probe!( class = "inference.generate.worker_started", request = ?request_for_blocking, - since_enter = ?gen_start.elapsed(), + since_enter = ?entered.elapsed(), "the blocking worker began this generation" ); let stop_refs: Vec<&str> = @@ -435,7 +437,7 @@ impl AIProviderAdapter for LlamaCppAdapter { class = "inference.generate.genes_ready", request = ?request_for_blocking, genes = genes_for_closure.len(), - since_enter = ?gen_start.elapsed(), + since_enter = ?entered.elapsed(), "her genes are loaded for this generation" ); let active_loras: Vec<(String, f32)> = genes_for_closure From c4e6ff86098ecc903cf15111e371278e77ea71c5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 22:37:30 -0600 Subject: [PATCH 27/41] The Core runs a turn to its end: no slicing (Joel, 2026-11-21: "you don't cut it up, run single lane; context switching is faster") The frame policy gave every ready turn a slice of a one-second service budget, so a turn in progress was cut into frames shared with every other ready mind. Measured on the M5 (56913f640b, 2026-11-21 04:14-04:29 UTC): 20 to 520 switches per turn at 12 to 25 ms each, up to 8.5 s of switch_ms inside one turn, and warm turns waiting ~600 ms for a slice before their first frame. Now the bound mind's started turn (prefilling or decoding) keeps the Core until it ends. When none is in progress, the next is the least remaining work discounted by wait (a long wait still comes forward; no mind starves), a tie keeping the bound mind. Each prefill chunk is the engine's full batch, bounded only by her checkpoint boundary. Deleted: SERVICE_BUDGET_MS and share_ms; the bound-time input to pick; Driver::bound_since; Driver::prefill_sample and its two updates; the `ready` count threaded through pick, step and prefill_chunk; Candidate::decoding (now `started`). driver.rs 941 -> 928 lines. The 2026-11-18 reason for slicing (short tails waiting 300-360 s behind cold prefills) is named in frame.rs; the 11-21 read shows 71-98% reuse on most turns. Whether a cold prompt still needs its own handling is measured on deploy, not assumed. check 0; persona_scheduler tests 12 pass (pick test rewritten for the new rule); ratchets vs origin/codex/frame-prefill-estimate 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../backends/persona_scheduler/driver.rs | 44 ++++------ .../backends/persona_scheduler/frame.rs | 82 ++++++++----------- 2 files changed, 51 insertions(+), 75 deletions(-) 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 de4ddca6aa..6fe1395929 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -140,8 +140,6 @@ struct Driver<'c, 'm> { model_id: String, /// The stop has suspended every mind: no new turn is taken. stopping: bool, - bound_since: Instant, - prefill_sample: Option<(usize, std::time::Duration)>, } /// The root resume: every mind the last stop published, held Warm (in RAM, bound when scheduled), @@ -257,11 +255,10 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { store: store.ok(), model_id: config.model.clone(), stopping: false, - bound_since: Instant::now(), - prefill_sample: None, }; // 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,8 +309,8 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { while let Ok(submission) = requests.try_recv() { driver.take(submission, &mut turns); } - let Some((index, ready)) = driver.pick(&turns) else { continue }; - match driver.step(&mut turns[index], ready) { + 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); @@ -577,11 +574,11 @@ impl Driver<'_, '_> { /// candidate; among candidates, `frame::pick` decides. A waiting turn's prefill is what she /// 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<(usize, std::num::NonZeroUsize)> { + 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, std::num::NonZeroUsize::MIN)); + return Some(0); } let mut seen = std::collections::HashSet::new(); let eligible: Vec = (0..turns.len()).filter(|&index| seen.insert(turns[index].id)).collect(); @@ -590,26 +587,25 @@ impl Driver<'_, '_> { .iter() .map(|&index| { let turn = &turns[index]; - let (decoding, remaining) = match &turn.phase { + 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).action.reused() } else { 0 }; // a mind never seen reuses nothing turn.prompt.len().saturating_sub(reused) })), - Phase::Prefilling { pos } => (false, turn.prompt.len().saturating_sub(*pos)), + Phase::Prefilling { pos } => (true, turn.prompt.len().saturating_sub(*pos)), Phase::Decoding { .. } => (true, 0), }; let waited_ms = record::whole_ms(turn.ready_since.elapsed()); - frame::Candidate { active: active == Some(turn.id), decoding, remaining, waited_ms } + frame::Candidate { active: active == Some(turn.id), started, remaining, waited_ms } }) .collect(); - let ready = std::num::NonZeroUsize::new(eligible.len())?; - frame::pick(&candidates, record::whole_ms(self.bound_since.elapsed())).map(|chosen| (eligible[chosen], ready)) + frame::pick(&candidates).map(|chosen| eligible[chosen]) } /// 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, ready: std::num::NonZeroUsize) -> Result { + fn step(&mut self, turn: &mut Turn) -> Result { if turn.req.response_tx.is_closed() { return Err(TurnError::CallerReleased); } @@ -621,7 +617,6 @@ impl Driver<'_, '_> { if self.engine.active() != Some(turn.id) { let switching = Instant::now(); self.switch_to(turn.id, turn.one_off)?; - self.bound_since = switching; turn.spent.switch += switching.elapsed(); turn.spent.switches += 1; } @@ -640,7 +635,7 @@ impl Driver<'_, '_> { let stepping = Instant::now(); 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, ready).map(|()| Advanced::Continues), 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(); @@ -736,17 +731,12 @@ impl Driver<'_, '_> { /// One chunk of her prompt from `pos`. The last chunk asks for logits and samples her first /// 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, ready: std::num::NonZeroUsize) -> Result<(), TurnError> { + 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.next_end(pos, turn.prompt.len()); - // A submission can arrive during this frame. Size the next native call from - // observed prefill time so a long prompt yields at the service boundary. - let started = Instant::now(); - let allowance = u128::from(frame::share_ms(ready)) * 1_000_000; - let count = self.prefill_sample.and_then(|(tokens, elapsed)| { - (tokens as u128 * allowance).checked_div(elapsed.as_nanos()) - }).map_or(1, |count| count.clamp(1, self.batch.get() as u128) as usize); - let end = pos.saturating_add(count).min(limit); + // 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)?; @@ -758,7 +748,6 @@ impl Driver<'_, '_> { if let Some(kind) = turn.boundaries.at(end) { self.keep_checkpoint(turn, kind, end)?; } - self.prefill_sample = Some((len, started.elapsed())); turn.phase = Phase::Prefilling { pos: end }; return Ok(()); } @@ -767,7 +756,6 @@ impl Driver<'_, '_> { 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)?; - self.prefill_sample = Some((len, started.elapsed())); turn.phase = Phase::Decoding { token, pos, generated: 0 }; Ok(()) } 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 954a258e72..d91c385b45 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs @@ -1,24 +1,27 @@ -//! 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." //! -//! Eligible turns share a one-second service budget. The bound mind advances until another -//! turn is due, then the oldest unserved turn gets the stream at the next landed frame. -// derived-or-floor: the conversational service requirement allows one second between eligible frames. -const SERVICE_BUDGET_MS: u64 = 1000; - -pub(super) fn share_ms(ready: std::num::NonZeroUsize) -> u64 { - SERVICE_BUDGET_MS.div_ceil(ready.get() as u64) -} +//! 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. +//! +//! So: the bound mind's turn, once started, keeps the Core until it ends. When no turn is in +//! progress, the next is the one with the least remaining work discounted by how long it has +//! waited, so a long wait brings any prompt forward and no mind starves; a tie keeps the mind +//! already bound, which saves a switch. -/// 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 admission or her most recent completed frame. @@ -33,49 +36,34 @@ impl Candidate { } } -/// The index of the turn the next frame advances, or `None` for no turns. -pub(super) fn pick(turns: &[Candidate], bound_ms: u64) -> Option { - let share_ms = share_ms(std::num::NonZeroUsize::new(turns.len())?); - if let Some((index, other)) = turns.iter().enumerate().filter(|(_, t)| !t.active).max_by_key(|(_, t)| t.waited_ms) { - if other.waited_ms >= SERVICE_BUDGET_MS || (other.waited_ms >= share_ms && bound_ms >= share_ms) { - return Some(index); - } - } - if let Some(decoding) = turns.iter().position(|turn| turn.active && (turn.decoding || (bound_ms < share_ms && turns.iter().any(|other| other.decoding)))) { - return Some(decoding); +/// The index of the turn the Core advances next, or `None` for no turns. +pub(super) fn pick(turns: &[Candidate]) -> Option { + 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_key(|(_, turn)| (turn.cost(), !turn.active)).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. + // 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_short_tail_never_waits_behind_a_long_prompt_and_an_overdue_turn_can_preempt_decode() { - assert_eq!(pick(&[], 0), None); - let long_active = turn(true, false, 60_000, 0); - let short = turn(false, false, 300, 0); - assert_eq!(pick(&[long_active, short], 0), Some(1), "the short tail switches in at the chunk boundary"); - + 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], 500), Some(0), "an overdue turn interrupts an answer"); - + 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], 0), Some(1), "ten minutes of waiting brings a long prompt forward"); - - assert_eq!(pick(&[turn(false, false, 500, 0), turn(true, false, 500, 0)], 0), Some(1), "a tie keeps the bound mind"); + 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"); } } From ad4126747ad8404fb655c4da82c4a4f462943e0d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 22:41:08 -0600 Subject: [PATCH 28/41] A finished turn's row carries its request id, so completions join their transitions by identity (Codex on #6207: terminal rows lacked it) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/inference/backends/persona_scheduler/driver.rs | 1 + .../src/inference/backends/persona_scheduler/record.rs | 3 +++ 2 files changed, 4 insertions(+) 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 6fe1395929..49424dd8d3 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -805,6 +805,7 @@ 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, 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 2c5f91b6ed..8461e90715 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/record.rs @@ -49,6 +49,8 @@ pub(super) enum Fact { /// 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, @@ -76,6 +78,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, From ce8a894e93c23f52dcaaaa676cbcac129881874b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 23:13:55 -0600 Subject: [PATCH 29/41] Every admitted turn ends in one terminal record; the four TurnPrompt literals #6207 missed compile - persona.engine.refused: a turn that ends without an answer (refused, failed, or a caller that hung up) now writes a terminal transition with its typed reason and time since admission; it wrote only a warning before, so it vanished from the receipts (independent review of #6179, finding 6). Every admitted turn ends in exactly one of this or persona.engine.turn. - core/continuum-core/tests/{qwen35_chat_pipeline_full,llamacpp_metal_throughput}.rs: four TurnPrompt literals lacked #6207's `request` field, so those (ignored) test targets did not compile; CI's lib-test jobs never built them, and I had checked only the engine and cognition crates (finding 1, my miss). cargo check -p continuum-engine -p continuum-core --tests: 0; persona_scheduler tests 12 pass; ratchets vs origin/codex/frame-prefill-estimate: 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../tests/llamacpp_metal_throughput.rs | 4 ++-- .../tests/qwen35_chat_pipeline_full.rs | 4 ++-- .../backends/persona_scheduler/driver.rs | 2 ++ .../backends/persona_scheduler/transition.rs | 18 ++++++++++++++++++ 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/core/continuum-core/tests/llamacpp_metal_throughput.rs b/core/continuum-core/tests/llamacpp_metal_throughput.rs index fa7066a8b4..38e00a5b14 100644 --- a/core/continuum-core/tests/llamacpp_metal_throughput.rs +++ b/core/continuum-core/tests/llamacpp_metal_throughput.rs @@ -132,7 +132,7 @@ async fn qwen35_4b_metal_throughput_via_bundled_llamacpp() { .submit_for_persona( GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), None, - TurnPrompt { text: "Reply OK.", stable_prefix: None }, 10, SamplingConfig::chat(), &[], &[]) + TurnPrompt { text: "Reply OK.", stable_prefix: None, request: None }, 10, SamplingConfig::chat(), &[], &[]) .expect("submit test turn") .collect() .await @@ -152,7 +152,7 @@ async fn qwen35_4b_metal_throughput_via_bundled_llamacpp() { .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 }, + TurnPrompt { text: "Count from 1 to 50, separated by commas.", stable_prefix: None, request: None }, 100, SamplingConfig::chat(), &[], diff --git a/core/continuum-core/tests/qwen35_chat_pipeline_full.rs b/core/continuum-core/tests/qwen35_chat_pipeline_full.rs index 3e75cfb606..27c8409e2b 100644 --- a/core/continuum-core/tests/qwen35_chat_pipeline_full.rs +++ b/core/continuum-core/tests/qwen35_chat_pipeline_full.rs @@ -96,7 +96,7 @@ async fn qwen35_persona_style_chat_produces_coherent_short_reply() { .submit_for_persona( GenerationAllocation::new(std::num::NonZeroU32::new(context_length).expect("explicit test allocation")), None, - TurnPrompt { text: &prompt, stable_prefix: None }, 2500, sampling, &stop, &[]) + TurnPrompt { text: &prompt, stable_prefix: None, request: None }, 2500, sampling, &stop, &[]) .expect("submit test turn") .collect() .await @@ -169,7 +169,7 @@ async fn qwen35_scheduler_json_grammar_returns_object() { .submit_for_persona( GenerationAllocation::new(std::num::NonZeroU32::new(32768).expect("explicit test allocation")), None, - TurnPrompt { text: &prompt, stable_prefix: None }, + TurnPrompt { text: &prompt, stable_prefix: None, request: None }, 128, sampling, &["<|im_end|>", "<|endoftext|>"], 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 49424dd8d3..8e68d566a1 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -320,6 +320,8 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { Err(refused) => { log.warn(&format!("turn refused: {refused}")); let turn = turns.remove(index); + let ended = transition::At::Refused { since_admit_ms: record::whole_ms(turn.submitted.elapsed()), reason: refused.to_string() }; + driver.transition(&turn, ended); driver.finish_one_off(&turn); driver.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error(refused.to_string()) }); } diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs index 95587cba0c..7e5f6ad820 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs @@ -27,6 +27,14 @@ pub(super) enum At { /// Whether reaching her took a switch from another mind. switched: bool, }, + /// 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. @@ -104,6 +112,16 @@ impl Transition { switched = switched, "a turn's first frame began" ), + 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, From 8e597e1bcd7268f91f007d09967056be6ef837b6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 23:33:55 -0600 Subject: [PATCH 30/41] One owner ends every admitted turn: answered, refused, stopping or closed, each with exactly one terminal record; a stop is acknowledged after its records are written Codex on ce8a894e93: a graceful stop drained admitted turns with only an Emit error, and the closed-submission path returned with turns still admitted: both left no terminal record. - driver/ending.rs (new): `Ending` (Answered, Refused(TurnError), Stopping, Closed) and `Driver::end`, the one place an admitted turn leaves the engine: it writes the turn row (answered) or persona.engine.refused with the reason, releases a one-off, and tells the caller. The loop's answer and error arms, the stop's drain and the closed channel all go through it. - A stop is handed back from `take` (`Stop`) and acknowledged by the loop only after `settle_records`: both outboxes drained, then a record-stage `Barrier` answered (FIFO), so its last records are written before the acknowledgement. The closed path settles them too. - `Advanced::Done` carries exactly an answer (`tokens_generated`, `elapsed_ms`) instead of any TokenEvent; the turn row moved from `step` into `end`. - driver.rs: 1008 -> 942 lines after the split (the 1,000-line gate). check -p continuum-engine --tests 0; check -p continuum-core --tests 0; persona_scheduler tests 12 pass; ratchets vs origin/codex/frame-prefill-estimate 0. Live stop replay follows on the PR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../backends/persona_scheduler/driver.rs | 64 ++++++++------- .../persona_scheduler/driver/ending.rs | 77 +++++++++++++++++++ .../backends/persona_scheduler/record.rs | 12 ++- 3 files changed, 124 insertions(+), 29 deletions(-) create mode 100644 core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs 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 8e68d566a1..dfd94c41ab 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -94,7 +94,10 @@ enum Tenure { OneOff, } +mod ending; mod history; + +use ending::{Ending, Stop}; use history::{Boundary, History, Boundaries}; /// A bound mind's blocks, as the tier that holds them in the context reports them. @@ -299,31 +302,36 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { ); } 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, its records are written, and Emit + // ends once it has drained what it holds. + Some(None) => { + for turn in std::mem::take(&mut turns) { + driver.end(turn, Ending::Closed); + } + driver.settle_records(&stages_on); + return; + } 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.finish_one_off(&turn); - 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); - let ended = transition::At::Refused { since_admit_ms: record::whole_ms(turn.submitted.elapsed()), reason: refused.to_string() }; - driver.transition(&turn, ended); - driver.finish_one_off(&turn); - driver.emit.send(emit::Out::End { answer: turn.answer, event: TokenEvent::Error(refused.to_string()) }); + driver.end(turns.remove(index), Ending::Refused(refused)); } } } @@ -395,7 +403,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). @@ -450,16 +459,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, suspended: self.suspend(turns) }), } } @@ -470,9 +482,8 @@ impl Driver<'_, '_> { /// it is the commit point. A mind not preserved is reported, never silently dropped. fn suspend(&mut self, turns: &mut Vec) -> Suspended { self.stopping = true; - for turn in turns.drain(..) { - self.finish_one_off(&turn); - 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(); @@ -653,9 +664,8 @@ impl Driver<'_, '_> { 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(TokenEvent::Done { tokens_generated, .. })) = &advanced { + 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 } @@ -766,10 +776,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. 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..0a254a98fd --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs @@ -0,0 +1,77 @@ +//! 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 written. + +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) suspended: Suspended, +} + +/// 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 once every record of the turns it ended is written. + pub(super) fn acknowledge(&mut self, stop: Stop, stages_on: &tokio::runtime::Handle) { + self.settle_records(stages_on); + report(stop.reply, stop.suspended); + } + + /// Every fact sent so far is written and every answer delivered: both outboxes drained, then the + /// record stage's barrier answered (it is FIFO). Before a stop is acknowledged, or the loop ends. + pub(super) fn settle_records(&mut self, stages_on: &tokio::runtime::Handle) { + self.flush(); + let (written, barrier) = tokio::sync::oneshot::channel(); + self.record.send(record::Fact::Barrier(written)); + stages_on.block_on(async { + self.drain().await; + if barrier.await.is_err() { + continuum_base::probe!(class = "persona.engine.records_unsettled", "the record stage ended before writing a stop's last records"); + } + }); + } +} 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 8461e90715..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,10 +40,13 @@ 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 reached a transition (admitted, first frame). + /// A turn reached a transition (admitted, frame started, first progress, refused). Transition(super::transition::Transition), - /// A turn ended. + /// 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), @@ -171,6 +174,11 @@ impl Stage for Record { 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"); + } + } } } } From 67abfaaf6a8ddd32f7f7f7089bbbb76eade8be08 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Fri, 20 Nov 2026 23:45:22 -0600 Subject: [PATCH 31/41] A stop waits only on its own records and says whether they were written; a stalled caller never holds it Codex on 8e597e1bcd: (1) a record stage that ended before answering the barrier still yielded a fully settled acknowledgement; (2) settle_records joined Emit's drain, so a caller that stopped reading her answer held the whole stop. - `settle` (driver/ending.rs), a function of the two outboxes: Emit is flushed but never awaited; the record outbox is drained, then the barrier awaited; a record stage that ended reads `Records::Unconfirmed` (probe persona.engine.records_unconfirmed). - `Suspended` carries `records: Records`. The suspend now returns `Suspension` (what it did natively); the acknowledgement assembles `Suspended` with the records outcome, so no placeholder is written and overwritten. The stop's custody report keeps its state (records are telemetry, never custody) and appends "the records of the turns it ended were not confirmed written" when so. - Tests (driver/ending_tests.rs, real flow stages): records read Written only when the record stage confirms them, Unconfirmed when it ended first; a stalled Emit sink with queued output never holds the settle, and its output is left for its caller. Mutation-checked: forcing Written fails the first. check -p continuum-engine -p continuum-core --tests 0; persona_scheduler tests 14 pass; ratchets 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../inference/backends/persona_scheduler.rs | 28 +++++++- .../backends/persona_scheduler/driver.rs | 10 +-- .../persona_scheduler/driver/ending.rs | 56 ++++++++++----- .../persona_scheduler/driver/ending_tests.rs | 72 +++++++++++++++++++ 4 files changed, 143 insertions(+), 23 deletions(-) create mode 100644 core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending_tests.rs diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index 946818b5a1..c81ab3aeb0 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -129,10 +129,23 @@ pub(super) enum Submission { Suspend(tokio::sync::oneshot::Sender), } +/// Whether a stop's last turn records were confirmed written by the record stage. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Records { + /// Every record sent before the stop is written (or the engine ended none). + #[default] + Written, + /// The record stage ended before confirming them: they may be lost. + Unconfirmed, +} + /// 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)>, } @@ -148,6 +161,15 @@ 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 written. +fn records_note(records: Records) -> &'static str { + match records { + Records::Written => "", + Records::Unconfirmed => "; the records of the turns it ended were not confirmed written", + } +} + + /// 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 @@ -171,10 +193,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"), } 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 dfd94c41ab..639412381b 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -97,7 +97,7 @@ enum Tenure { mod ending; mod history; -use ending::{Ending, Stop}; +use ending::{Ending, Stop, Suspension}; use history::{Boundary, History, Boundaries}; /// A bound mind's blocks, as the tier that holds them in the context reports them. @@ -471,7 +471,7 @@ impl Driver<'_, '_> { self.admit(req, turns); None } - Submission::Suspend(reply) => Some(Stop { reply, suspended: self.suspend(turns) }), + Submission::Suspend(reply) => Some(Stop { reply, suspension: self.suspend(turns) }), } } @@ -480,7 +480,7 @@ 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 std::mem::take(turns) { self.end(turn, Ending::Stopping); @@ -493,7 +493,7 @@ impl Driver<'_, '_> { } else { minds.iter().map(|mind| (mind.0, why.clone())).collect() }; - Suspended { preserved: 0, retained } + Suspension { preserved: 0, retained } }; if let Some(id) = self.engine.retiring() { if let Err(why) = self.retire_previous() { @@ -526,7 +526,7 @@ 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 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 index 0a254a98fd..2de2ef12a4 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs @@ -3,12 +3,23 @@ //! `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 written. +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) suspended: Suspended, + 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. @@ -55,23 +66,36 @@ impl Driver<'_, '_> { self.emit.send(emit::Out::End { answer: turn.answer, event }); } - /// Acknowledge a stop once every record of the turns it ended is written. + /// Acknowledge a stop: its native suspend result as it is, with whether the records of the turns + /// it ended were confirmed written. pub(super) fn acknowledge(&mut self, stop: Stop, stages_on: &tokio::runtime::Handle) { - self.settle_records(stages_on); - report(stop.reply, stop.suspended); + let records = self.settle_records(stages_on); + let Suspension { preserved, retained } = stop.suspension; + report(stop.reply, Suspended { records, preserved, retained }); } - /// Every fact sent so far is written and every answer delivered: both outboxes drained, then the - /// record stage's barrier answered (it is FIFO). Before a stop is acknowledged, or the loop ends. - pub(super) fn settle_records(&mut self, stages_on: &tokio::runtime::Handle) { - self.flush(); - let (written, barrier) = tokio::sync::oneshot::channel(); - self.record.send(record::Fact::Barrier(written)); - stages_on.block_on(async { - self.drain().await; - if barrier.await.is_err() { - continuum_base::probe!(class = "persona.engine.records_unsettled", "the record stage ended before writing a stop's last records"); - } - }); + /// 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)) } } + +/// Every record sent so far is written, confirmed by the record stage answering a barrier it reaches +/// after them (it is FIFO). 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) -> Records { + emit.flush(); + let (written, answered) = oneshot::channel(); + record.send(barrier(written)); + record.drain().await; + if answered.await.is_ok() { + Records::Written + } 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..579f6ad78c --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending_tests.rs @@ -0,0 +1,72 @@ +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, + 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 fully 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_written_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_eq!(settle(&mut emit, &mut record, Fact::Barrier).await, Records::Written); + + 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).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_eq!(settle(&mut emit, &mut record, Fact::Barrier).await, Records::Written); + assert!(emit.waiting() > 0, "the stalled sink's output is left for its caller, not awaited"); +} From 6505cb43d32fc8fb65612ce5286bde434c60a3f6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 00:10:10 -0600 Subject: [PATCH 32/41] A replay can be served as the resident herself, so it runs as realistically as her live turn (Joel, 2026-11-21: "Replay should be as realistic as regular mode") cognition/replay-request gave every replay a fresh persona id, so the engine served it as a stranger with nothing cached: every replayed turn was a cold prefill, unlike live turns that reuse 71-98% of their prompt (the M5 windows of 2026-11-21). - `identity`: `isolated` (the default, unchanged: a fresh mind, cold) or `resident` (the source persona's own mind, so her parked blocks are reused exactly as her next live turn would reuse them). - The engine's identity and the capture's owner are now separate: the capture is always owned by a fresh replay identity, so a replay never enters her prompt history or her learning, whichever mind served it. - The result names the identity it was served as. - A resident replay interleaving with her live loop is safe (one serial queue per mind; reuse is checked against the actual prompt) but spoils a measurement, so a measuring run holds and despawns her first. No cross-layer hosting check (cognition must not import mind). The validator (request_replay tests) extends the isolation test: a resident replay is served as her own mind and its capture is still owned by a separate replay identity. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/request_replay.rs | 46 +++++++++++++++++-- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/core/continuum-cognition/src/cognition/request_replay.rs b/core/continuum-cognition/src/cognition/request_replay.rs index 16db201d0d..55cd0c348e 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)] + #[ts(optional)] + pub identity: Option, +} + +/// 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. 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.unwrap_or_default() { + 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.unwrap_or_default() }; 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 changes live persona memory. 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: None, }; 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: Some(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); From 2f7fc55ce1a4992d58a1aec8c49423a2b75ce8ec Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 00:16:12 -0600 Subject: [PATCH 33/41] Replay: say what a resident replay changes (her native KV and the checkpoint a stop saves from it), never her memory, history or learning (Codex on 6505cb43d3) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-cognition/src/cognition/request_replay.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/core/continuum-cognition/src/cognition/request_replay.rs b/core/continuum-cognition/src/cognition/request_replay.rs index 55cd0c348e..a0db5a47f8 100644 --- a/core/continuum-cognition/src/cognition/request_replay.rs +++ b/core/continuum-cognition/src/cognition/request_replay.rs @@ -57,9 +57,10 @@ 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. 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. + /// 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, } @@ -341,7 +342,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, 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 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; From e61b5cffe11767f50ae6321ba0ea7c5d7b6a70fa Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 01:10:12 -0600 Subject: [PATCH 34/41] A refused decode reports what the engine held; replay identity is a defaulted field, not an Option - persona.engine.decode_refused (continuum-persona-llama unified_tier): when llama_decode refuses a step, the probe records the step (from, tokens), the context geometry (n_ctx, n_ctx_seq, n_seq_max, n_batch, n_ubatch) and every execution stream's occupant and highest position. The M5, 2026-11-21: cold 26-36k resident replays were refused "no KV slot" (llama_decode returned 1) about 31 s into prefill, and the source alone cannot tell other streams' cells, full-batch chunks or fragmentation apart (Codex's request: measure before inferring a cause). Its first dependency on continuum-base (the floor) and tracing. - ReplayRequestParams::identity is `ReplayIdentity` with a serde default (absent = isolated) instead of `Option` + unwrap_or_default at two sites (the unwrap ratchet). check -p continuum-persona-llama -p continuum-engine -p continuum-cognition --tests 0; request_replay tests pass; persona-llama builds with metal; ratchets vs origin/fable/run-to-end 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/request_replay.rs | 11 ++++---- core/continuum-persona-llama/Cargo.toml | 2 ++ .../src/unified_tier.rs | 25 +++++++++++++++---- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/core/continuum-cognition/src/cognition/request_replay.rs b/core/continuum-cognition/src/cognition/request_replay.rs index a0db5a47f8..3209b41bdf 100644 --- a/core/continuum-cognition/src/cognition/request_replay.rs +++ b/core/continuum-cognition/src/cognition/request_replay.rs @@ -46,8 +46,7 @@ pub struct ReplayRequestParams { /// 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)] - #[ts(optional)] - pub identity: Option, + pub identity: ReplayIdentity, } /// Which mind the engine serves a replay as. @@ -308,7 +307,7 @@ fn prepare( let request_id = Uuid::new_v4().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.unwrap_or_default() { + let served_as = match p.identity { ReplayIdentity::Isolated => replay, ReplayIdentity::Resident => persona, }; @@ -317,7 +316,7 @@ fn prepare( 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(), identity: p.identity.unwrap_or_default() }; + let provenance = Provenance { input_comparison, model_from_response, persona, cursor: p.selected.clone(), identity: p.identity }; Ok(Prepared { request, call: PromptCall { @@ -496,7 +495,7 @@ mod tests { omit_message_indices: Vec::new(), expected_request_sha256: None, tool_schema_override: None, - identity: None, + identity: ReplayIdentity::Isolated, }; let read = || prompt_capture::detail(dir.path(), persona, &cursor).expect("original capture"); @@ -524,7 +523,7 @@ mod tests { 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: Some(ReplayIdentity::Resident), ..p.clone() }; + 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"); 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)); From 6d1b6663562e07f1fc0ec73e264bf5295dc64078 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 01:25:12 -0600 Subject: [PATCH 35/41] The Core refuses at the door a prompt its stream cannot hold, with the numbers The M5, 2026-11-21 (persona.engine.decode_refused, e61b5cffe1): a 26,633-token resident replay was admitted to a 24,576-token stream (n_ctx 49,152 / n_seq_max 2), prefilled for ~31 s, and refused by the engine at the chunk that crossed the end (from 22,623 + 2,048 tokens). The engine spent the work and then failed; the object model's Core answers Infeasible when a need exceeds its cap. - admission.rs (new): `StreamCapacity` (the applied geometry's n_ctx_seq) admits a prompt only with room for one generated token, else `Infeasible { prompt_tokens, capacity }` (typed, with Display). - The driver holds its `StreamCapacity` from the geometry it applied, checks every turn at `admit`, tells the caller with the numbers, and records persona.engine.infeasible keyed by the request id. A refused turn was never admitted, so it has no other transition. - Live deliberation already fits prompts to the published n_ctx_seq (delib.turn.demand context_window=24576 tonight); this guards every caller that does not fit its own: replays, and external drivers. persona_scheduler tests 15 pass (the admission validator added); check engine + core tests 0; ratchets vs origin/fable/run-to-end 0; driver.rs 953 lines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../inference/backends/persona_scheduler.rs | 1 + .../backends/persona_scheduler/admission.rs | 48 +++++++++++++++++++ .../backends/persona_scheduler/driver.rs | 14 +++++- .../backends/persona_scheduler/transition.rs | 13 +++++ 4 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 core/continuum-engine/src/inference/backends/persona_scheduler/admission.rs diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index c81ab3aeb0..1c2c8d7ad7 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -25,6 +25,7 @@ mod frame; mod reuse; mod geometry; mod sampling; +mod admission; mod transition; pub use geometry::{EngineGeometry, EngineState, Incarnation, Requested}; 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 639412381b..fb3d8c17ed 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -18,7 +18,7 @@ use uuid::Uuid; use super::geometry::StopsOnExit; use continuum_flow::{Outbox, StageInput}; -use super::{emit, frame, preserve, record, reuse, sampling, transition, 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; @@ -125,6 +125,8 @@ 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. @@ -233,6 +235,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); @@ -249,6 +252,7 @@ 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(), @@ -555,6 +559,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) => { diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs index 7e5f6ad820..f33fa16f40 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/transition.rs @@ -27,6 +27,9 @@ pub(super) enum At { /// 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 { @@ -112,6 +115,16 @@ impl Transition { 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, From 60a618097365be3afe1ed9eca0237a0dd826657f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 01:53:20 -0600 Subject: [PATCH 36/41] Record native persona tier dependencies in the workspace lockfile --- Cargo.lock | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 8c0667d62d..8f8bb46c93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3603,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", ] From 8f386fb4e163a2a0b2385c516af54568ddee8b8b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 03:16:35 -0600 Subject: [PATCH 37/41] Answer the #6208 review: no starving tie, no answer end lost at close, no "written" the log never confirmed Codex's full review at 162fbe5fa7, each finding with a validator that fails on the old code: - P1 frame.rs: the cost was integer division, so an aged and a fresh one-token tail both cost zero and affinity won every tie; a bound mind that kept arriving starved an older one. Costs now compare exactly (cross-multiplied); an equal cost goes to the longer wait; only a full tie keeps the bound mind. Validator: repeated arrivals of the bound mind, the older mind served on its first round. - P2 driver.rs + ending.rs: when every submission handle dropped, the loop flushed Emit once and dropped what a full Emit still held with the driver, answer ends included. `Driver::close` ends every turn, settles records, and hands Emit to a drain owner on the stage runtime (`hand_off`), in order; the engine thread never waits on Emit and the stop acknowledgement stays independent. Validator: a saturated Emit stage, its outbox handed off, all eight outputs in order. - P2 record.rs / probe_file_sink.rs: `Records::Written` confirmed only that the tracing callbacks returned, and the sink dropped write/flush errors. The probe floor now owns one count of failed probe-log writes (continuum-base `probe_writes`), the sink counts each line it cannot write, and a settle reads `Records::Processed { write_failures }` since the previous settle; durability is never claimed. Validator: a sink on a disk that refuses writes counts the failure; a settle reports a failure counted in its window, once. Touched files leave clean: the probe sink's unbounded single-file `new` had no production caller (boot rolls) and is deleted, its 12 tests move to the rolling constructor; its serialization names its disk boundary; `DEFAULT_MAX_LOG_FILES` is now the appender's `KEEP` (8, what the broker's rotation pool budgets), not a second count of 7. engine persona_scheduler 18 pass, kernel probe_file_sink 16, base probe_writes 1; mutation of the tie order and of the hand-off each fails its validator; check engine/kernel/core tests 0; ratchets vs origin/codex/frame-prefill-estimate 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-base/src/lib.rs | 1 + core/continuum-base/src/probe_writes.rs | 43 +++++++ .../inference/backends/persona_scheduler.rs | 29 +++-- .../backends/persona_scheduler/driver.rs | 14 +-- .../persona_scheduler/driver/ending.rs | 48 ++++++-- .../persona_scheduler/driver/ending_tests.rs | 63 +++++++++- .../backends/persona_scheduler/frame.rs | 40 +++++-- .../src/routing/probe_file_sink.rs | 110 ++++++------------ .../src/routing/probe_file_sink/tests.rs | 90 +++++++++----- 9 files changed, 291 insertions(+), 147 deletions(-) create mode 100644 core/continuum-base/src/probe_writes.rs 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-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index 1c2c8d7ad7..6c990ea087 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -130,16 +130,26 @@ pub(super) enum Submission { Suspend(tokio::sync::oneshot::Sender), } -/// Whether a stop's last turn records were confirmed written by the record stage. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +/// 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 is written (or the engine ended none). - #[default] - Written, + /// 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)] @@ -162,11 +172,12 @@ 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 written. -fn records_note(records: Records) -> &'static str { +/// 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::Written => "", - Records::Unconfirmed => "; the records of the turns it ended were not confirmed written", + 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(), } } 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 fb3d8c17ed..43bede4a75 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -136,6 +136,8 @@ struct Driver<'c, 'm> { /// 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 @@ -258,6 +260,7 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { 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(), @@ -311,15 +314,8 @@ pub(super) fn run(model: &Model, config: &SchedulerConfig, start: Start) { driver.acknowledge(stop, &stages_on); } } - // Every handle dropped: every admitted turn ends, its records are written, and Emit - // ends once it has drained what it holds. - Some(None) => { - for turn in std::mem::take(&mut turns) { - driver.end(turn, Ending::Closed); - } - driver.settle_records(&stages_on); - return; - } + // 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; 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 index 2de2ef12a4..21728e4896 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs @@ -1,8 +1,9 @@ //! 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 written. +//! 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; @@ -66,8 +67,8 @@ impl Driver<'_, '_> { self.emit.send(emit::Out::End { answer: turn.answer, event }); } - /// Acknowledge a stop: its native suspend result as it is, with whether the records of the turns - /// it ended were confirmed written. + /// 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; @@ -76,20 +77,45 @@ impl Driver<'_, '_> { /// 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)) + 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 }) } -/// Every record sent so far is written, confirmed by the record stage answering a barrier it reaches -/// after them (it is FIFO). 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) -> Records { +/// 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 (written, answered) = oneshot::channel(); - record.send(barrier(written)); + let (processed, answered) = oneshot::channel(); + record.send(barrier(processed)); record.drain().await; if answered.await.is_ok() { - Records::Written + 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 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 index 579f6ad78c..f0c6125e9d 100644 --- 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 @@ -5,6 +5,8 @@ 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<()>), } @@ -36,22 +38,22 @@ fn one() -> Capacity { Capacity::granted(NonZeroUsize::MIN) } -// what this catches: a stop acknowledged as fully settled when the record stage ended before +// 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_written_only_when_the_record_stage_confirms_them() { +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_eq!(settle(&mut emit, &mut record, Fact::Barrier).await, Records::Written); + 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).await, Records::Unconfirmed, "a record stage that ended cannot confirm"); + 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: @@ -67,6 +69,57 @@ async fn a_stalled_emit_sink_never_holds_the_stop() { let (record_input, _record) = spawn_stage(Answers, one()); let mut record = Outbox::new(record_input); - assert_eq!(settle(&mut emit, &mut record, Fact::Barrier).await, Records::Written); + 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"); +} 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 d91c385b45..d60c6d2fe5 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs @@ -12,8 +12,8 @@ //! //! So: the bound mind's turn, once started, keeps the Core until it ends. When no turn is in //! progress, the next is the one with the least remaining work discounted by how long it has -//! waited, so a long wait brings any prompt forward and no mind starves; a tie keeps the mind -//! already bound, which saves a switch. +//! waited, so a long wait brings any prompt forward and no mind starves; an equal cost goes to the +//! longer wait, and only a full tie keeps the mind already bound, which saves a switch. /// A turn as the pick sees it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -29,10 +29,18 @@ pub(super) struct Candidate { } 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)) + /// Whether this turn goes before `other`: less remaining work discounted by age (tokens per + /// second waited, plus one so a fresh turn is its own size), compared exactly by cross- + /// multiplying, so short tails never round to a tie; then the longer wait; only then the mind + /// already bound, which saves a switch. Codex on #6208 at 162fbe5fa7: integer division made an + /// aged and a fresh one-token tail both cost zero, and affinity won every such tie, so a bound + /// mind that kept arriving starved an older one. + fn before(&self, other: &Self) -> std::cmp::Ordering { + 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)) } } @@ -41,7 +49,7 @@ pub(super) fn pick(turns: &[Candidate]) -> Option { 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)] @@ -66,4 +74,22 @@ mod tests { 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-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"); + } From 8c7d4f172d43ad8211ed7fa111fb0228be252513 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 03:42:31 -0600 Subject: [PATCH 38/41] Shutdown never closes a stage's intake: the ends a closing driver handed off reach their callers Codex on 8f386fb4e1: `Driver::close` hands a full Emit outbox to its drain owner, then the driver thread called `StageWorker::stop()` on both stages before that task necessarily ran, so the ends it had not yet pushed came back `Stopped` and were dropped. A stage already ends by itself once its last producer is gone and it has handled what it took, and after `run` returns the only producers left are the driver's (dropped) and the drain owner's (dropped when drained), so the thread now waits on `driver::finish`, which joins both stages and never stops them. Startup failures and early returns drop their inputs too, so the join always returns. Validator: a full Emit handed off, then `finish` exactly as the thread runs it: all eight ends reach the caller in order. Mutating `finish` to stop before joining fails it. persona_scheduler 19 pass; check engine + core tests 0; ratchets vs origin/codex/frame-prefill-estimate 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../inference/backends/persona_scheduler.rs | 6 ++--- .../backends/persona_scheduler/driver.rs | 1 + .../persona_scheduler/driver/ending.rs | 12 +++++++++ .../persona_scheduler/driver/ending_tests.rs | 25 +++++++++++++++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler.rs b/core/continuum-engine/src/inference/backends/persona_scheduler.rs index 6c990ea087..638f1010bc 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler.rs @@ -243,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/driver.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs index 43bede4a75..e68ec8dced 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver.rs @@ -98,6 +98,7 @@ mod ending; mod history; 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. 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 index 21728e4896..4a8bfc6427 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/ending.rs @@ -99,6 +99,18 @@ pub(super) fn hand_off(mut emit: Outbox, on: &tokio::runti 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). 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 index f0c6125e9d..0ecbf1abf7 100644 --- 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 @@ -123,3 +123,28 @@ async fn a_closed_engine_hands_a_full_emit_to_a_drain_owner_in_order() { } 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"); +} From 391ca2f3b6390502de4479b56370dfbd63a6dc20 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 04:28:30 -0600 Subject: [PATCH 39/41] Fit native context memory to the physical stream layout --- .../src/inference/in_process_engine.rs | 4 ++ .../src/inference/llama_server.rs | 2 + .../src/inference/llama_server/control.rs | 2 + .../inference/llama_server/control_impl.rs | 4 ++ .../inference/llama_server/stream_layout.rs | 51 +++++++++++++++++++ .../src/inference/llama_server/tests.rs | 4 ++ .../src/modules/serving_daemon/host_fit.rs | 22 ++++++-- .../src/modules/serving_daemon/launch.rs | 14 +++-- .../src/modules/serving_daemon/tests.rs | 4 ++ .../src/modules/serving_daemon/tests/dyno.rs | 4 +- docs/architecture/CONTINUUM-ENGINE.md | 5 ++ 11 files changed, 105 insertions(+), 11 deletions(-) create mode 100644 core/continuum-engine/src/inference/llama_server/stream_layout.rs 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-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/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 From ab7c9cc1354e4766d8a7326d531762780b07e67e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 05:58:29 -0600 Subject: [PATCH 40/41] Give overdue turns priority at the next scheduling boundary --- .../backends/persona_scheduler/frame.rs | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) 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 d60c6d2fe5..20b73de65d 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs @@ -11,9 +11,8 @@ //! prompt still needs its own handling is measured, not assumed. //! //! So: the bound mind's turn, once started, keeps the Core until it ends. When no turn is in -//! progress, the next is the one with the least remaining work discounted by how long it has -//! waited, so a long wait brings any prompt forward and no mind starves; an equal cost goes to the -//! longer wait, and only a full tie keeps the mind already bound, which saves a switch. +//! 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 pick sees it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -29,13 +28,13 @@ pub(super) struct Candidate { } impl Candidate { - /// Whether this turn goes before `other`: less remaining work discounted by age (tokens per - /// second waited, plus one so a fresh turn is its own size), compared exactly by cross- - /// multiplying, so short tails never round to a tie; then the longer wait; only then the mind - /// already bound, which saves a switch. Codex on #6208 at 162fbe5fa7: integer division made an - /// aged and a fresh one-token tail both cost zero, and affinity won every such tie, so a bound - /// mind that kept arriving starved an older one. fn before(&self, other: &Self) -> std::cmp::Ordering { + 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)) @@ -60,6 +59,15 @@ mod tests { Candidate { active, started, remaining, waited_ms } } + #[test] + 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. From 9dff3fb8191cc465294106630d5946ace7000c2a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sat, 21 Nov 2026 06:09:08 -0600 Subject: [PATCH 41/41] Document the interactive wait threshold used at turn boundaries --- .../src/inference/backends/persona_scheduler/frame.rs | 2 ++ 1 file changed, 2 insertions(+) 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 20b73de65d..9378cbecf8 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs @@ -29,6 +29,8 @@ pub(super) struct Candidate { impl Candidate { 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)