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..88a43e9c8e 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}; @@ -92,36 +92,8 @@ enum Tenure { OneOff, } -/// The tokens her blocks hold, and her checkpoint at her last view's end while what she holds still -/// runs through it. -#[derive(Default)] -struct History { - held: Vec, - kept: [Option; 2], -} - -/// Her checkpoint and what makes it valid: she held exactly `held[..end]` under `basis` when it was -/// taken, and nothing she holds below `end` has changed since (a cut below it drops it). -struct KeptCheckpoint { - blocks: llama::PersonaCheckpoint, - end: usize, - basis: Basis, -} - -/// Her checkpoint holds her recurrent rows in host memory. -impl Footprint for KeptCheckpoint { - fn held(&self) -> Held { - Held::host(self.blocks.bytes() as u64) - } -} - -/// 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> { @@ -135,28 +107,8 @@ impl Footprint for Bound<'_, '_, '_> { } } -impl History { - /// Keep only her first `len` tokens; a cut below her checkpoint's end drops the checkpoint. - fn cut(&mut self, len: usize) { - self.held.truncate(len); - for slot in &mut self.kept { - if slot.as_ref().is_some_and(|kept| kept.end > len) { - *slot = None; - } - } - } - - /// Where `prompt` under `basis` would start for her, whose blocks were computed under `under` - /// (`reuse::choose`), deciding nothing and moving nothing: the bind uses it to resume her, the - /// frame to size her turn's prefill. - fn reuse(&self, under: &Basis, prompt: &[i32], basis: &Basis) -> reuse::Reuse { - let kept = self.kept.iter().flatten().map(|kept| reuse::Kept { end: kept.end, basis: &kept.basis }); - reuse::choose(reuse::History { basis: under, tokens: &self.held }, kept, reuse::History { basis, tokens: prompt }) - } -} - /// Where `prompt` under `basis` would start for `her`. -fn reuse_for(her: &Mind, prompt: &[i32], basis: &Basis) -> reuse::Reuse { +fn reuse_for(her: &Mind, prompt: &[i32], basis: &Basis) -> reuse::Decision { her.parts().tokens.reuse(&her.parts().genome, prompt, basis) } @@ -170,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 @@ -184,6 +138,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), @@ -212,7 +168,7 @@ fn resume(tier: &mut UnifiedTier<'_, '_>, preserved: &mut preserve::Preserved, m match tier.read_file(MindId { persona: id, epoch }, &preserved.path(&mind.blocks)) { Ok(blocks) => { continuum_base::probe!(class = "persona.engine.resumed", persona = %mind.persona, tokens = mind.held.len() as u64, "a mind came back from her preserved blocks"); - let parts = Parts { blocks, tokens: History { held: mind.held, kept: Default::default() }, genome: Basis { genes: mind.basis }, learning: (), decode: Tenure::Resident }; + let parts = Parts { blocks, tokens: History::from(mind.held), genome: Basis { genes: mind.basis }, learning: (), decode: Tenure::Resident }; parked.insert(id, Mind::new(id, epoch, parts)); } Err(refused) => { @@ -292,12 +248,15 @@ 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, 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 +289,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()) }); } } @@ -359,10 +320,11 @@ struct Turn { sampler: llama::Sampler, phase: Phase, submitted: Instant, + ready_since: Instant, spent: Spent, /// Where her view ends in `prompt` (CONTINUUM-ENGINE 4.15): a prefill chunk ends exactly there /// and she is checkpointed, so her next act resumes from it. `None` for a turn with no view. - boundaries: [Option; 2], + boundaries: Boundaries, /// Her answer, as Emit numbers it. answer: emit::AnswerSeq, /// Raised by Emit when her answer has ended on a stop sequence or her caller hung up; read at @@ -390,6 +352,7 @@ struct Spent { start: &'static str, checkpoint_ms: u64, first_step: Option, + longest_gap: std::time::Duration, switch: std::time::Duration, prefill: std::time::Duration, decode: std::time::Duration, @@ -484,15 +447,27 @@ 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 { - return Suspended { preserved: 0, retained: vec![(Uuid::nil(), "this node has no home to preserve minds in".into())] }; + 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 } }; - 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); + if let Some(id) = self.engine.retiring() { + if let Err(why) = self.retire_previous() { + return blocked(id.0, format!("copy-out of {:?} blocked preservation: {why}", id.0)); + } } + let Some(mut store) = self.store.take() else { + return blocked(Uuid::nil(), "this node has no home to preserve minds in".into()); + }; // 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(); @@ -523,7 +498,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))?; @@ -556,7 +531,9 @@ 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(); + 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) => { tell(&req.response_tx, TokenEvent::Error(refused.to_string())); @@ -568,7 +545,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, 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(); @@ -579,28 +556,32 @@ 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)), Phase::Decoding { .. } => (true, 0), }; - let waited_ms = record::whole_ms(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).map(|chosen| eligible[chosen]) + 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) -> Result { + 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()); } 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 +595,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.ready_since = stepped; let took = stepped.saturating_duration_since(stepping); if decoding { turn.spent.decode += took; @@ -638,9 +620,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 { @@ -648,8 +629,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"), @@ -670,42 +651,38 @@ impl Driver<'_, '_> { /// Rewind the active mind to her kept checkpoint (taken out and put back, so the engine can read /// it while it moves her). fn rewind_to_checkpoint(&mut self, end: usize) -> Result<(), TurnError> { - let slots = &mut self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens.kept; - let index = slots.iter().position(|slot| slot.as_ref().is_some_and(|kept| kept.end == end)).ok_or(TurnError::NoneActive)?; - let kept = slots[index].take(); - let Some(kept) = kept else { return Err(TurnError::NoneActive) }; - let rewound = self.engine.rewind_active(&kept.blocks); - self.record(|her| her.tokens.kept[index] = Some(kept))?; + let snapshot = self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens.take_at(end).ok_or(TurnError::NoneActive)?; + let rewound = self.engine.rewind_active(snapshot.blocks()); + self.record(|her| her.tokens.put_back(snapshot))?; Ok(rewound?) } /// Checkpoint the active mind at her view's end (`end` tokens held), reusing her checkpoint's /// buffers. A refused take keeps none, so a later act restarts instead of rewinding to a stale one. - fn keep_checkpoint(&mut self, turn: &mut Turn, index: usize, end: usize) -> Result<(), TurnError> { + fn keep_checkpoint(&mut self, turn: &mut Turn, kind: Boundary, end: usize) -> Result<(), TurnError> { let taking = Instant::now(); - let previous = self.engine.active_mut().ok_or(TurnError::NoneActive)?.parts_mut().tokens.kept[index].take(); - let mut blocks = match previous.map(|kept| kept.blocks).or_else(llama::PersonaCheckpoint::new) { - Some(blocks) => blocks, - None => return Ok(()), // the host could not allocate a checkpoint: she restarts next act, named in its row - }; - let 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 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))?; + } turn.spent.checkpoint_ms += record::whole_ms(taking.elapsed()); Ok(()) } /// 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: 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 end = (pos + self.batch.get()).min(limit); + 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); let chunk = turn.prompt[pos..end].to_vec(); let last = end == turn.prompt.len(); let from = i32::try_from(pos).map_err(|_| TurnError::TooLong)?; @@ -714,9 +691,10 @@ 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 }; return Ok(()); } @@ -725,6 +703,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(()) } @@ -780,10 +759,11 @@ 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), switches: turn.spent.switches, switch_ms: ms(turn.spent.switch), prefill_ms: ms(turn.spent.prefill), @@ -830,10 +810,17 @@ 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); + self.live_one_offs.remove(&turn.id); + } + } + + /// A paused one-off keeps her blocks until she finishes, just like a paused resident. fn retire_previous(&mut self) -> Result<(), TurnError> { let Some(previous) = self.engine.finish_retirement()? else { return Ok(()) }; - if resident(&previous) { + if resident(&previous) || self.live_one_offs.contains(&previous.id()) { self.parked.insert(previous.id(), previous); } Ok(()) diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs new file mode 100644 index 0000000000..a717d295fd --- /dev/null +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/driver/history.rs @@ -0,0 +1,175 @@ +use super::{reuse, Basis, Footprint, Held}; + +/// The tokens her blocks hold, and her checkpoint at her last view's end while what she holds still +/// runs through it. +#[derive(Default)] +pub(super) struct History { + pub(super) held: Vec, + /// View end, latest learned prefix, and earliest still-valid learned prefix. + kept: [Option; 3], +} + +/// Her checkpoint and what makes it valid: she held exactly `held[..end]` under `basis` when it was +/// taken, and nothing she holds below `end` has changed since (a cut below it drops it). +struct KeptCheckpoint { + blocks: llama::PersonaCheckpoint, + end: usize, + basis: Basis, +} + +/// Her checkpoint holds her recurrent rows in host memory. +impl Footprint for KeptCheckpoint { + fn held(&self) -> Held { + Held::host(self.blocks.bytes() as u64) + } +} + +/// Her token history and her checkpoint. Her blocks in the context are reported by the tier that +/// binds them; [`Bound`] is that child's view. +impl Footprint for History { + fn held(&self) -> Held { + self.kept + .iter() + .fold(self.held.held(), |bytes, kept| bytes + kept.held()) + } +} + +impl History { + /// Keep only her first `len` tokens; a cut below her checkpoint's end drops the checkpoint. + pub(super) fn cut(&mut self, len: usize) { + self.held.truncate(len); + for slot in &mut self.kept { + if slot.as_ref().is_some_and(|kept| kept.end > len) { + *slot = None; + } + } + } + + /// Where `prompt` under `basis` would start for her, whose blocks were computed under `under` + /// (`reuse::choose`), deciding nothing and moving nothing: the bind uses it to resume her, the + /// frame to size her turn's prefill. + pub(super) fn reuse(&self, under: &Basis, prompt: &[i32], basis: &Basis) -> reuse::Decision { + let kept = self.kept.iter().flatten().map(|kept| reuse::Kept { + end: kept.end, + basis: &kept.basis, + }); + reuse::choose( + reuse::History { + basis: under, + tokens: &self.held, + }, + kept, + reuse::History { + basis, + tokens: prompt, + }, + ) + } +} + +#[derive(Clone, Copy)] +pub(super) enum Boundary { + View, + Learned, +} + +pub(super) struct Boundaries { + pub(super) view: Option, + pub(super) learned: Option, +} +impl Boundaries { + fn entries(&self) -> impl Iterator { + [ + (Boundary::View, self.view), + (Boundary::Learned, self.learned), + ] + .into_iter() + .filter_map(|(kind, end)| Some((kind, end?))) + } + pub(super) fn next_end(&self, pos: usize, prompt_end: usize) -> usize { + self.entries() + .map(|(_, end)| end) + .filter(|end| *end > pos) + .min() + .unwrap_or(prompt_end) // unwrap_or: the prompt ends the final frame + } + pub(super) fn at(&self, end: usize) -> Option { + self.entries() + .find_map(|(kind, pos)| (pos == end).then_some(kind)) + } +} +impl From> for History { + fn from(held: Vec) -> Self { + Self { + held, + ..Self::default() + } + } +} + +impl History { + pub(super) fn deepest(&self) -> Option { + self.kept.iter().flatten().map(|s| s.end).max() + } + pub(super) fn take_at(&mut self, end: usize) -> Option { + let (slot, entry) = self + .kept + .iter_mut() + .enumerate() + .find(|(_, entry)| entry.as_ref().is_some_and(|s| s.end == end))?; + Some(Snapshot { + slot, + checkpoint: entry.take()?, + }) + } + pub(super) fn put_back(&mut self, snapshot: Snapshot) { + self.kept[snapshot.slot] = Some(snapshot.checkpoint); + } + fn slot(&mut self, kind: Boundary) -> &mut Option { + let [view, learned, _] = &mut self.kept; + match kind { + Boundary::View => view, + Boundary::Learned => learned, + } + } + pub(super) fn capture_buffer( + &mut self, + kind: Boundary, + end: usize, + ) -> Option { + if let Boundary::Learned = kind { + let [_, latest, earliest] = &mut self.kept; + if latest.as_ref().is_some_and(|prior| { + prior.end < end && earliest.as_ref().is_none_or(|s| prior.end < s.end) + }) { + std::mem::swap(latest, earliest); + } + } + self.slot(kind) + .take() + .map(|s| s.blocks) + .or_else(llama::PersonaCheckpoint::new) + } + pub(super) fn save( + &mut self, + kind: Boundary, + blocks: llama::PersonaCheckpoint, + end: usize, + basis: &Basis, + ) { + *self.slot(kind) = Some(KeptCheckpoint { + blocks, + end, + basis: basis.clone(), + }); + } +} +pub(super) struct Snapshot { + slot: usize, + checkpoint: KeptCheckpoint, +} +impl Snapshot { + pub(super) fn blocks(&self) -> &llama::PersonaCheckpoint { + &self.checkpoint.blocks + } +} diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/frame.rs index 322b68e98e..954a258e72 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,14 @@ //! 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. +// 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) +} /// A turn as the frame sees it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -23,7 +21,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 +34,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(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); } turns @@ -60,18 +64,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, diff --git a/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs b/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs index e5eac7267a..b6be1f523d 100644 --- a/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs +++ b/core/continuum-engine/src/inference/backends/persona_scheduler/reuse.rs @@ -54,9 +54,7 @@ impl Miss { } /// The tokens two sequences share from their start. -pub(super) fn common_prefix(a: &[i32], b: &[i32]) -> usize { - a.iter().zip(b).take_while(|(x, y)| x == y).count() -} +pub(super) use continuum_persona_engine::turn::common_prefix; /// One of her checkpoints as reuse sees it: the tokens it holds through (exclusive end) and its basis. #[derive(Clone, Copy)] @@ -69,28 +67,33 @@ pub(super) struct Kept<'a, B> { /// the furthest one both histories hold unchanged under the same genes. Her head's checkpoint /// serves a turnover, which changes her view but not her head (the M5, 2026-11-19, 48a1dc80cd: 17 /// of 30 turns re-prefilled from 0 behind an unchanged head, ~180k of 422,847 tokens). -pub(super) fn choose<'a, B: PartialEq + 'a>(held: History<'_, B>, kept: impl IntoIterator>, next: History<'_, B>) -> Reuse { - let (held_tokens, prompt, basis) = (held.tokens, next.tokens, next.basis); - // The prompt extends her whole held history (her own generated tokens included): append. - if let continuum_persona_engine::turn::Prefill::Append { from } = continuum_persona_engine::turn::plan(held, next) { - return Reuse::Append { from }; +pub(super) struct Decision { + pub shared: usize, + pub action: Reuse, +} + +pub(super) fn choose<'a, B: PartialEq + 'a>(held: History<'_, B>, kept: impl IntoIterator>, next: History<'_, B>) -> Decision { + let comparison = held.compare(&next); + let shared = comparison.shared; + let decide = |action| Decision { shared, action }; + let (held, prompt, basis) = (held.tokens, next.tokens, next.basis); + if let continuum_persona_engine::turn::Prefill::Append { from } = comparison.prefill { + return decide(Reuse::Append { from }); } - let held = held_tokens; let mut kept = kept.into_iter().peekable(); if kept.peek().is_none() { - return Reuse::Restart(if held.is_empty() { Miss::Cold } else { Miss::NoCheckpoint }); + return decide(Reuse::Restart(if held.is_empty() { Miss::Cold } else { Miss::NoCheckpoint })); } let mut same_genes = kept.filter(|kept| kept.basis == basis).peekable(); if same_genes.peek().is_none() { - return Reuse::Restart(Miss::Basis); + return decide(Reuse::Restart(Miss::Basis)); } // A checkpoint's end must be held unchanged by both, and leave a token to sample from. - let shared = common_prefix(held, prompt); - same_genes + decide(same_genes .map(|kept| kept.end) .filter(|end| *end > 0 && *end < prompt.len() && *end <= shared) .max() - .map_or(Reuse::Restart(Miss::Diverged), |from| Reuse::Rewind { from }) + .map_or(Reuse::Restart(Miss::Diverged), |from| Reuse::Rewind { from })) } #[cfg(test)] @@ -113,20 +116,20 @@ mod tests { let mut next: Vec = (0..80).collect(); next.extend([900, 901, 902]); // a new trailer and her call, rendered differently let kept = [Kept { end: 80, basis: &genes }]; - assert_eq!(choose(h(&held, &genes), kept, h(&next, &genes)), Reuse::Rewind { from: 80 }); + assert_eq!(choose(h(&held, &genes), kept, h(&next, &genes)).action, Reuse::Rewind { from: 80 }); let mut early: Vec = (0..40).collect(); early.push(777); // her view itself changed (a new epoch): before her checkpoint early.extend(41..90); - assert_eq!(choose(h(&held, &genes), kept, h(&early, &genes)), Reuse::Restart(Miss::Diverged)); + assert_eq!(choose(h(&held, &genes), kept, h(&early, &genes)).action, Reuse::Restart(Miss::Diverged)); - assert_eq!(choose(h(&held, &genes), kept, h(&next, &"tuned")), Reuse::Restart(Miss::Basis)); - assert_eq!(choose(h(&held, &genes), [], h(&next, &genes)), Reuse::Restart(Miss::NoCheckpoint)); - assert_eq!(choose(h(&[], &genes), [], h(&next, &genes)), Reuse::Restart(Miss::Cold)); + assert_eq!(choose(h(&held, &genes), kept, h(&next, &"tuned")).action, Reuse::Restart(Miss::Basis)); + assert_eq!(choose(h(&held, &genes), [], h(&next, &genes)).action, Reuse::Restart(Miss::NoCheckpoint)); + assert_eq!(choose(h(&[], &genes), [], h(&next, &genes)).action, Reuse::Restart(Miss::Cold)); let mut extends = held.clone(); extends.extend([5, 6]); - assert_eq!(choose(h(&held, &genes), kept, h(&extends, &genes)), Reuse::Append { from: 100 }); + assert_eq!(choose(h(&held, &genes), kept, h(&extends, &genes)).action, Reuse::Append { from: 100 }); } // what this catches (the M5, 2026-11-19, 48a1dc80cd: 17 of 30 turns re-prefilled from 0 behind @@ -140,17 +143,17 @@ mod tests { let kept = [Kept { end: 80, basis: &genes }, Kept { end: 20, basis: &genes }]; let mut turned: Vec = (0..20).collect(); turned.extend(500..560); // a new epoch: her view re-rendered behind the same head - assert_eq!(choose(h(&held, &genes), kept, h(&turned, &genes)), Reuse::Rewind { from: 20 }); + assert_eq!(choose(h(&held, &genes), kept, h(&turned, &genes)).action, Reuse::Rewind { from: 20 }); let mut trailer: Vec = (0..80).collect(); trailer.push(900); - assert_eq!(choose(h(&held, &genes), kept, h(&trailer, &genes)), Reuse::Rewind { from: 80 }); + assert_eq!(choose(h(&held, &genes), kept, h(&trailer, &genes)).action, Reuse::Rewind { from: 80 }); let mut head_changed: Vec = vec![777]; head_changed.extend(1..90); - assert_eq!(choose(h(&held, &genes), kept, h(&head_changed, &genes)), Reuse::Restart(Miss::Diverged)); + assert_eq!(choose(h(&held, &genes), kept, h(&head_changed, &genes)).action, Reuse::Restart(Miss::Diverged)); let mixed = [Kept { end: 80, basis: &"tuned" }, Kept { end: 20, basis: &genes }]; - assert_eq!(choose(h(&held, &genes), mixed, h(&trailer, &genes)), Reuse::Rewind { from: 20 }, "only her checkpoints under these genes count"); + assert_eq!(choose(h(&held, &genes), mixed, h(&trailer, &genes)).action, Reuse::Rewind { from: 20 }, "only her checkpoints under these genes count"); } } diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs b/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs index be3d129ece..7125d412f2 100644 --- a/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs +++ b/core/continuum-engine/src/inference/llamacpp_adapter/chat_turn.rs @@ -153,18 +153,37 @@ pub(super) struct ParsedTurn { pub(super) tool_calls: Option>, } +/// Native generation output and the effective stop set used to produce it. +pub(super) struct GeneratedTurn<'a> { + pub(super) written: &'a str, + pub(super) tokens: usize, + pub(super) end: GenerationEnd, + pub(super) stops: &'a [String], +} + impl ParsedTurn { /// A turn that kept no text and no call, told apart by its raw tail and the stop it ended on: a /// stop string firing where her call began, the model ending inside its thinking, or a call the /// parse dropped (Aiko, 20 turns from 15:36Z 2026-11-19, text 0, reasoning only). - pub(super) fn probe_if_empty(&self, written: &str, tokens: usize, end: GenerationEnd, stops: &[String]) { + pub(super) fn probe_if_empty(&self, output: GeneratedTurn<'_>, request: &TextGenerationRequest) { + let GeneratedTurn { written, tokens, end, stops } = output; if !self.text.is_empty() || self.tool_calls.as_ref().is_some_and(|calls| !calls.is_empty()) { return; } + // Diagnostic only: correlate a Qwen function marker with this render's own request. + // A marker in generated text is never authority to dispatch a call. + let marker = written.rsplit_once("')) + .map(|(name, _)| name) + .filter(|name| !name.is_empty() && name.len() <= 128 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"/._-".contains(&b))); + let offered = marker.map(|name| request.tools.as_deref().into_iter().flatten() + .chain(request.tail_tools.as_deref().into_iter().flatten()).any(|tool| tool.name == name)); let chars: Vec = written.chars().collect(); let tail: String = chars[chars.len().saturating_sub(160)..].iter().collect(); continuum_base::probe!( class = "inference.turn.wrote_nothing", + persona = ?request.persona_id, + function_marker = ?marker, + offered_on_request = ?offered, tokens = tokens as u64, end = ?end, stop = ?stops.iter().find(|stop| written.ends_with(stop.as_str())), diff --git a/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs b/core/continuum-engine/src/inference/llamacpp_adapter/provider.rs index 990f4c3e88..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); + let output = super::chat_turn::GeneratedTurn { written: &written, tokens, end, stops: &stop_owned }; + turn.probe_if_empty(output, &request); (turn.text, turn.reasoning, turn.tool_calls) } Err(refused) => return Err(refused.to_string()), diff --git a/core/continuum-persona-engine/src/engine.rs b/core/continuum-persona-engine/src/engine.rs index fd4f799225..ceb0859a64 100644 --- a/core/continuum-persona-engine/src/engine.rs +++ b/core/continuum-persona-engine/src/engine.rs @@ -111,6 +111,11 @@ where self.roles.active().map(Identified::persona) } + /// The units held across the active, staged and retiring roles. + pub fn units(&self) -> impl Iterator { + self.roles.units() + } + /// The active mind's own state (her tokens, her position), never the tier she runs on. pub fn active_mut(&mut self) -> Option<&mut U> { self.roles.active_mut() diff --git a/core/continuum-persona-engine/src/engine/tests.rs b/core/continuum-persona-engine/src/engine/tests.rs index 1717a35eff..41efbffd4f 100644 --- a/core/continuum-persona-engine/src/engine/tests.rs +++ b/core/continuum-persona-engine/src/engine/tests.rs @@ -243,6 +243,8 @@ fn a_refused_copy_out_is_finished_before_the_next_switch_and_given_back_once() { assert!(matches!(h.engine.finish_retirement(), Err(RetireError::CopyOut(_))), "still refused"); assert_eq!(h.engine.retiring(), Some(id(1)), "she stays in custody"); + let held: Vec<_> = h.engine.units().map(|mind| mind.id()).collect(); + assert_eq!(held, [id(2), id(1)], "both active and retiring minds remain in custody"); h.refuse.set(None); assert!(matches!(h.engine.finish_retirement(), Err(RetireError::Release(RetireRefusal::NotLanded { .. }))), "begun, not landed"); land_last(&h.moves); diff --git a/core/continuum-persona-engine/src/pipeline/roles.rs b/core/continuum-persona-engine/src/pipeline/roles.rs index fcbaebf43b..84581c117d 100644 --- a/core/continuum-persona-engine/src/pipeline/roles.rs +++ b/core/continuum-persona-engine/src/pipeline/roles.rs @@ -83,11 +83,11 @@ enum Retiring { Moving(InFlight), } -impl Retiring { - fn persona(&self) -> PersonaId { +impl Retiring { + fn unit(&self) -> &U { match self { - Self::AwaitingCopyOut(unit) => unit.persona(), - Self::Moving(moving) => moving.unit.persona(), + Self::AwaitingCopyOut(unit) => unit, + Self::Moving(moving) => &moving.unit, } } } @@ -115,6 +115,13 @@ impl Roles { self.active.as_ref() } + /// All units this Core owns, including those in flight. + pub fn units(&self) -> impl Iterator { + self.active.iter() + .chain(self.next.iter().map(|next| &next.unit)) + .chain(self.retiring.iter().map(Retiring::unit)) + } + /// Mutable access to the active mind only: decoding touches nobody else. pub fn active_mut(&mut self) -> Option<&mut U> { self.active.as_mut() @@ -125,7 +132,7 @@ impl Roles { } pub fn retiring(&self) -> Option { - self.retiring.as_ref().map(Retiring::persona) + self.retiring.as_ref().map(|role| role.unit().persona()) } /// The exact copy-out to begin for the mind awaiting it (her persona, epoch, direction out): the diff --git a/core/continuum-persona-engine/src/turn.rs b/core/continuum-persona-engine/src/turn.rs index 0ac78dbc5a..e0f997f076 100644 --- a/core/continuum-persona-engine/src/turn.rs +++ b/core/continuum-persona-engine/src/turn.rs @@ -36,9 +36,27 @@ pub enum Prefill { /// (`Append { from: len - 1 }`, after the tier drops that one position). An empty prompt cannot be /// sampled from and restarts, as does a mind with nothing held. pub fn plan(held: History<'_, B>, turn: History<'_, B>) -> Prefill { - let extends = held.basis == turn.basis && !held.tokens.is_empty() && turn.tokens.starts_with(held.tokens); - if !extends || turn.tokens.is_empty() { - return Prefill::Restart; + held.compare(&turn).prefill +} + +/// One comparison of the native token vectors, used for planning and accounting. +pub struct Compared { + pub shared: usize, + pub prefill: Prefill, +} + +pub fn common_prefix(a: &[i32], b: &[i32]) -> usize { + a.iter().zip(b).take_while(|(left, right)| left == right).count() +} + +impl History<'_, B> { + pub fn compare(&self, next: &History<'_, B>) -> Compared { + let shared = common_prefix(self.tokens, next.tokens); + let prefill = if shared > 0 && shared == self.tokens.len() && self.basis == next.basis { + Prefill::Append { from: shared.min(next.tokens.len() - 1) } + } else { + Prefill::Restart + }; + Compared { shared, prefill } } - Prefill::Append { from: held.tokens.len().min(turn.tokens.len() - 1) } } diff --git a/core/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