diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 9423a8bc..e6b39bf7 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -6,6 +6,7 @@ pub use crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive; #[path = "backend_measurement.rs"] mod measurement; use crate::{ + conversation::resident::{ResidentConversations, ResidentPolicy}, model_binding::qwen4exp_input::{InputBindingError, InputConstants, ModelBinding}, qwen_forward::{ contract::{Dimension, Position, TokenId}, @@ -1353,19 +1354,31 @@ fn serve_load( return Ok(()); } let mut unload_reply = None; - let mut prefix_cache: Option> = None; + // One live continuation, plus (operator opt-in) parked conversations with + // the Original's best-prefix / slot / byte-budget policy. Disabled (the + // default) this is exactly the former single resident prefix. + let mut conversations = ResidentConversations::>::new( + ResidentPolicy::from_environment().unwrap_or_else(|reason| { + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-conversation configuration-rejected reason={reason}; parking disabled" + ); + ResidentPolicy::disabled() + }), + ); while !shared.shutdown.load(Ordering::Acquire) { match rx.recv_timeout(Duration::from_millis(100)) { Err(mpsc::RecvTimeoutError::Timeout) => continue, Err(_) => break, Ok(Command::Load(_, _, reply)) => { - prefix_cache = None; + conversations.clear(); let _ = reply.send(Err(exhausted( "unload the existing model before another load", ))); } Ok(Command::Unload(candidate, reply)) => { - prefix_cache = None; + conversations.clear(); if candidate != loaded { let _ = reply.send(Err(invalid("unknown loaded model handle"))); } else { @@ -1376,19 +1389,19 @@ fn serve_load( Ok(Command::Generate(candidate, request, cancel, reply)) => { let _guard = ActiveGuard(shared); if candidate != loaded { - prefix_cache = None; + conversations.clear(); let _ = reply.send(Err(invalid("unknown loaded model handle"))); continue; } if !shared.ready.load(Ordering::Acquire) { - prefix_cache = None; + conversations.clear(); let _ = reply.send(Err(unavailable("native model is not ready"))); continue; } let prompt = match prepare_prompt(&tokenizer, &request, config.context_tokens) { Ok(prompt) => prompt, Err(error) => { - prefix_cache = None; + conversations.clear(); let _ = reply.send(Err(error)); continue; } @@ -1396,33 +1409,38 @@ fn serve_load( let (sink, stream) = GenerationSink::bounded_channel(QUEUE) .map_err(|_| unavailable("generation queue unavailable"))?; if reply.send(Ok(stream)).is_err() { - prefix_cache = None; + conversations.clear(); continue; } // Take before attempting any work: no failed/cancelled request - // may leave a reusable earlier entry behind. - let old = prefix_cache.take().filter(|entry| { - if entry.loaded != loaded - || !append_compatible(&entry.continuation.tokens, &prompt) - { - return false; - } - match entry.continuation.decoder.validate_resume( - &binding, - &entry.session, - &entry.continuation.product, - &entry.continuation.tokens, - ) { - Ok(()) => true, - Err(crate::qwen_forward::contract::Error::CudaExecution) => { - // Dropping a poisoned session cannot mint a fresh - // healthy session on the same actor/context. - shared.ready.store(false, Ordering::Release); - false + // may leave the entry it consumed behind. A candidate must be + // for this handle, a strict token-prefix of the prompt, and + // still validate against the device; a live session that is + // not the one continuing is parked (when enabled), not lost. + let old = conversations + .take_for(&prompt, |entry| { + if entry.loaded != loaded + || !append_compatible(&entry.continuation.tokens, &prompt) + { + return false; } - Err(_) => false, - } - }); + match entry.continuation.decoder.validate_resume( + &binding, + &entry.session, + &entry.continuation.product, + &entry.continuation.tokens, + ) { + Ok(()) => true, + Err(crate::qwen_forward::contract::Error::CudaExecution) => { + // Dropping a poisoned session cannot mint a fresh + // healthy session on the same actor/context. + shared.ready.store(false, Ordering::Release); + false + } + Err(_) => false, + } + }) + .map(|resumed| resumed.session); let (mut session, resume) = match old { Some(entry) => (entry.session, Some(entry.continuation)), None => ( @@ -1567,17 +1585,28 @@ fn serve_load( } } if let Some(continuation) = pending_prefix { - prefix_cache = Some(PrefixSession { - loaded: loaded.clone(), - session, - continuation, - }); + let committed = continuation.tokens.clone(); + conversations.publish( + &committed, + PrefixSession { + loaded: loaded.clone(), + session, + continuation, + }, + ); + } + { + use std::io::Write; + for event in conversations.take_events() { + let _ = writeln!(std::io::stderr().lock(), "leleka-{event}"); + } } } } } shared.ready.store(false, Ordering::Release); - drop(prefix_cache); + conversations.clear(); + drop(conversations); { use std::io::Write; let moe = moe_cache.counters(); diff --git a/crates/leleka-runtime/src/conversation/mod.rs b/crates/leleka-runtime/src/conversation/mod.rs index c0cb2913..69c542ca 100644 --- a/crates/leleka-runtime/src/conversation/mod.rs +++ b/crates/leleka-runtime/src/conversation/mod.rs @@ -20,6 +20,7 @@ pub mod memory; pub mod model; #[cfg(any(test, all(target_os = "linux", target_arch = "x86_64")))] pub mod original; +pub mod resident; pub mod retention; pub mod snapshot; #[cfg(test)] diff --git a/crates/leleka-runtime/src/conversation/resident.rs b/crates/leleka-runtime/src/conversation/resident.rs new file mode 100644 index 00000000..7af21b5f --- /dev/null +++ b/crates/leleka-runtime/src/conversation/resident.rs @@ -0,0 +1,527 @@ +//! Parking of device-resident sessions: the conversation policy as the Rust +//! serving actor uses it. +//! +//! The Rust actor's sessions are immutable-producer states that stay on the +//! device (`PrefixSession`), so "parking" a conversation means keeping its +//! session object alive beside the live one instead of copying it to host RAM. +//! The policy is the Original's, unchanged: one LIVE session continues without +//! a copy when its committed tokens are a prefix of the request; otherwise the +//! best parked conversation (longest reusable prefix; ties to the most +//! recently parked) is swapped in and the outgoing one is parked, subject to a +//! slot count and a byte budget with oldest-first eviction. Parking is opt in +//! (budget 0 disables it and leaves exactly one live session). +//! +//! Differences from the host-snapshot manager are structural, not policy: +//! +//! * bytes are an ACCOUNTING ESTIMATE of retained device state +//! ([`ResidentPolicy::estimate`]), not an allocation fact, and there is no +//! host-RAM admission (nothing is copied to host memory); +//! * no turn-boundary checkpoints: a retained draft/target product pair can +//! only resume at the end of the tokens it committed (the single position +//! whose head product exists), so a mid-prompt checkpoint has nothing to +//! resume from. The checkpoint chain belongs to the snapshot path +//! ([`super::manager`]). + +use super::cache::{CheckpointKey, ConversationCache, ConversationImageKey, ParkedConversation}; + +/// Operator policy for parking resident sessions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ResidentPolicy { + /// Retained device bytes the parked sessions may account for; 0 disables parking. + pub budget_bytes: usize, + pub slots: usize, + /// Accounting: state every session holds regardless of length (GDN + /// recurrence + convolution for 36 layers, PLE history). + pub fixed_bytes: usize, + /// Accounting: retained K/V per committed token (12 QSA layers, 2 KV + /// heads, K and V in fp16). + pub bytes_per_token: usize, +} + +impl ResidentPolicy { + /// Parking off: exactly one live continuation, as before. + pub const fn disabled() -> Self { + Self { + budget_bytes: 0, + slots: 4, + fixed_bytes: 118_038_528, + bytes_per_token: 24_576, + } + } + + pub fn enabled(&self) -> bool { + self.budget_bytes != 0 && self.slots != 0 + } + + /// Accounted bytes of a session that committed `tokens` tokens. + pub fn estimate(&self, tokens: usize) -> usize { + self.fixed_bytes + .saturating_add(tokens.saturating_mul(self.bytes_per_token)) + } + + /// Strict parse of the operator knobs (`LELEKA_CONVERSATION_CACHE_MIB`, + /// `LELEKA_CONVERSATION_CACHE_SLOTS`). Absent means default; anything that + /// is not a plain decimal number in range is an error (never a guess). + pub fn from_values(mib: Option<&str>, slots: Option<&str>) -> Result { + fn number(text: &str, max: u64) -> Result { + if text.is_empty() || text.len() > 12 || !text.bytes().all(|b| b.is_ascii_digit()) { + return Err("invalid conversation cache setting"); + } + let value: u64 = text + .parse() + .map_err(|_| "invalid conversation cache setting")?; + if value > max { + return Err("conversation cache setting out of range"); + } + Ok(value) + } + let mut policy = Self::disabled(); + if let Some(text) = mib { + policy.budget_bytes = usize::try_from(number(text, 1 << 22)? << 20) + .map_err(|_| "conversation cache too large")?; + } + if let Some(text) = slots { + policy.slots = number(text, 64)? as usize; + } + Ok(policy) + } + + /// The process environment's operator knobs. + pub fn from_environment() -> Result { + let read = |name: &str| match std::env::var(name) { + Ok(value) => Ok(Some(value)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(_) => Err("invalid conversation cache setting"), + }; + let (mib, slots) = ( + read("LELEKA_CONVERSATION_CACHE_MIB")?, + read("LELEKA_CONVERSATION_CACHE_SLOTS")?, + ); + Self::from_values(mib.as_deref(), slots.as_deref()) + } +} + +/// A conversation held beside the live one: its committed tokens, the bytes it +/// is accounted for, and the session itself. +pub struct ParkedResident { + ids: Vec, + bytes: usize, + session: S, +} + +impl ParkedConversation for ParkedResident { + fn live_ids(&self) -> &[i32] { + &self.ids + } + fn live_images(&self) -> &[ConversationImageKey] { + &[] + } + fn checkpoint_keys(&self) -> Vec> { + Vec::new() + } + fn cvec(&self) -> bool { + true + } + fn bytes(&self) -> usize { + self.bytes + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ResumeSource { + Live, + Parked, +} + +/// The session a request continues from. +pub struct Resumed { + pub session: S, + /// Committed tokens the session holds (all of them are reused). + pub tokens: usize, + pub source: ResumeSource, +} + +pub struct ResidentConversations { + policy: ResidentPolicy, + live: Option>, + cache: ConversationCache>, + events: Vec, +} + +fn as_ids(tokens: &[u32]) -> Option> { + tokens.iter().map(|&t| i32::try_from(t).ok()).collect() +} + +impl ResidentConversations { + pub fn new(policy: ResidentPolicy) -> Self { + let cache = ConversationCache::new(policy.budget_bytes, policy.slots); + Self { + policy, + live: None, + cache, + events: Vec::new(), + } + } + + pub fn policy(&self) -> ResidentPolicy { + self.policy + } + pub fn parked(&self) -> usize { + self.cache.size() + } + pub fn has_live(&self) -> bool { + self.live.is_some() + } + pub fn cache(&self) -> &ConversationCache> { + &self.cache + } + pub fn take_events(&mut self) -> Vec { + std::mem::take(&mut self.events) + } + + /// Drop every session (unload, a rejected request, an unhealthy device). + pub fn clear(&mut self) { + self.live = None; + self.cache = ConversationCache::new(self.policy.budget_bytes, self.policy.slots); + } + + /// Park the live session if the policy allows; otherwise it is released. + /// `held` is a session already taken out for the exchange. + fn park_live(&mut self, held: usize) { + let Some(live) = self.live.take() else { return }; + if !self.cache.enabled() { + return; + } + // No checkpoint chain here, so nothing is superseded: the explicit + // reservation is `make_room`'s oldest-first eviction. + if !self.cache.make_room(live.bytes, held) { + self.events.push(format!( + "conversation cache: skip parking ({} MiB exceeds available budget)", + live.bytes >> 20 + )); + return; + } + let tokens = live.ids.len(); + let stored = self.cache.put(live, held).is_ok(); + self.events.push(format!( + "conversation cache: {} {tokens} tokens; parked={} bytes={} evictions={}", + if stored { "parked" } else { "skipped" }, + self.cache.size(), + self.cache.bytes(), + self.cache.evictions() + )); + } + + /// Choose the session a request for `prompt` continues from, removing it + /// from the store, and park the outgoing live session when it is not the + /// one continuing. + /// + /// `usable` is the actor's own admission of a candidate (same model + /// handle, committed tokens a prefix, device state still validates); a + /// candidate it rejects is dropped. The live candidate may reuse a prompt + /// equal to its committed tokens; parked candidates keep the Original's + /// rule that the last prompt token always starts the next window. + pub fn take_for( + &mut self, + prompt: &[u32], + mut usable: impl FnMut(&S) -> bool, + ) -> Option> { + let Some(ids) = as_ids(prompt) else { + self.live = None; + return None; + }; + // Strict equality of every committed token; length may equal the prompt. + let live_ok = self.live.as_ref().is_some_and(|l| { + !l.ids.is_empty() && l.ids.len() <= ids.len() && ids[..l.ids.len()] == l.ids[..] + }); + let mut live_len = if live_ok { + self.live.as_ref().map_or(0, |l| l.ids.len()) + } else { + 0 + }; + if live_ok + && let Some(l) = &self.live + && !usable(&l.session) + { + self.live = None; + live_len = 0; + } + let best = self.cache.best(prompt, &[], true); + let mut incoming = if best.tokens as usize > live_len { + self.cache.take(best.index) + } else { + None + }; + if let Some(p) = &incoming + && !usable(&p.session) + { + self.events + .push("conversation cache: discard unusable parked session".into()); + incoming = None; + } + let swap = incoming.is_some() || live_len == 0; + if swap { + let held = incoming.as_ref().map_or(0, |p| p.bytes); + self.park_live(held); + } + if let Some(p) = incoming { + self.events.push(format!( + "conversation cache: restored {} tokens; parked={} bytes={}", + p.ids.len(), + self.cache.size(), + self.cache.bytes() + )); + return Some(Resumed { + tokens: p.ids.len(), + session: p.session, + source: ResumeSource::Parked, + }); + } + if live_len > 0 { + let l = self.live.take()?; + return Some(Resumed { + tokens: l.ids.len(), + session: l.session, + source: ResumeSource::Live, + }); + } + None + } + + /// A completed request's session becomes the live continuation. + pub fn publish(&mut self, committed: &[u32], session: S) { + match as_ids(committed) { + Some(ids) if !ids.is_empty() => { + let bytes = self.policy.estimate(ids.len()); + self.live = Some(ParkedResident { + ids, + bytes, + session, + }); + } + _ => self.live = None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn policy(budget_gib: usize, slots: usize) -> ResidentPolicy { + ResidentPolicy { + budget_bytes: budget_gib << 30, + slots, + fixed_bytes: 100 << 20, + bytes_per_token: 20_000, + } + } + fn toks(salt: u32, n: u32) -> Vec { + (0..n).map(|i| salt * 1000 + i).collect() + } + + #[test] + fn disabled_policy_keeps_exactly_the_old_single_continuation() { + let mut store = ResidentConversations::<&'static str>::new(ResidentPolicy::disabled()); + store.publish(&toks(1, 10), "a"); + let mut p = toks(1, 10); + p.push(7); + let r = store.take_for(&p, |_| true).unwrap(); + assert_eq!( + (r.session, r.tokens, r.source), + ("a", 10, ResumeSource::Live) + ); + store.publish(&toks(1, 12), "a2"); + // Another conversation replaces it; nothing is parked. + assert!(store.take_for(&toks(2, 9), |_| true).is_none()); + assert_eq!(store.parked(), 0); + assert!(!store.has_live()); + } + + #[test] + fn an_identical_prompt_may_reuse_the_live_session_but_not_a_parked_one() { + let mut store = ResidentConversations::::new(policy(8, 4)); + store.publish(&toks(1, 10), 1); + assert_eq!( + store.take_for(&toks(1, 10), |_| true).unwrap().tokens, + 10, + "live: equal length allowed" + ); + store.publish(&toks(1, 10), 1); + assert!(store.take_for(&toks(2, 5), |_| true).is_none()); // parks 1 + assert_eq!(store.parked(), 1); + let mut other = toks(2, 5); + other.push(1); + store.publish(&toks(2, 5), 2); + // The parked session holds exactly the prompt: the last token must be read. + assert!(store.take_for(&toks(1, 10), |_| true).is_none()); + assert_eq!(store.parked(), 2, "both conversations are parked now"); + } + + #[test] + fn a_b_a_swaps_through_the_cache_and_prefers_the_longest_prefix() { + let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); + store.publish(&toks(1, 20), "A"); + assert!(store.take_for(&toks(2, 8), |_| true).is_none()); + store.publish(&toks(2, 8), "B"); + // A again, one token longer. + let mut a = toks(1, 20); + a.push(5); + let r = store.take_for(&a, |_| true).unwrap(); + assert_eq!( + (r.session, r.tokens, r.source), + ("A", 20, ResumeSource::Parked) + ); + assert_eq!(store.parked(), 1, "B was parked in exchange"); + store.publish(&a, "A2"); + // A branch of A that diverges after 12 tokens finds nothing reusable + // in A2 (not a prefix), but B is unrelated: nothing resumes. + let mut branch = toks(1, 12); + branch.push(999_999); + assert!(store.take_for(&branch, |_| true).is_none()); + assert_eq!(store.parked(), 2, "A2 is parked rather than lost"); + let events = store.take_events(); + assert!( + events.iter().any(|e| e.contains("restored 20 tokens")), + "{events:?}" + ); + } + + #[test] + fn the_longest_parked_prefix_wins_and_ties_go_to_the_newest() { + let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); + store.publish(&toks(1, 10), "short"); + assert!(store.take_for(&toks(3, 3), |_| true).is_none()); + store.publish(&toks(1, 14), "long"); + assert!(store.take_for(&toks(4, 3), |_| true).is_none()); + store.publish(&toks(1, 14), "long-dup"); + assert!(store.take_for(&toks(5, 3), |_| true).is_none()); + // All three share toks(1, 10) as a prefix of the request. + let mut request = toks(1, 14); + request.push(0); + let r = store.take_for(&request, |_| true).unwrap(); + assert_eq!( + (r.session, r.tokens), + ("long-dup", 14), + "equal length: the most recently parked" + ); + } + + #[test] + fn slots_and_bytes_bound_the_parked_set_oldest_first() { + let mut store = ResidentConversations::::new(policy(8, 2)); + for salt in 1..=4u32 { + store.publish(&toks(salt, 10), salt); + assert!(store.take_for(&toks(100 + salt, 3), |_| true).is_none()); + } + assert_eq!(store.parked(), 2); + assert_eq!(store.cache().evictions(), 2); + // The two oldest conversations are gone, the two newest remain. + for (salt, expect) in [(1, false), (2, false), (3, true), (4, true)] { + let mut p = toks(salt, 10); + p.push(1); + let hit = store.cache().best(&p, &[], true).tokens > 0; + assert_eq!(hit, expect, "conversation {salt}"); + } + // A budget smaller than one session parks nothing. + let mut tiny = ResidentConversations::::new(ResidentPolicy { + budget_bytes: 1 << 20, + ..policy(8, 4) + }); + tiny.publish(&toks(1, 10), 1); + assert!(tiny.take_for(&toks(2, 3), |_| true).is_none()); + assert_eq!(tiny.parked(), 0); + let events = tiny.take_events(); + assert!( + events.iter().any(|e| e.contains("skip parking")), + "{events:?}" + ); + } + + #[test] + fn unusable_candidates_are_dropped_not_resumed() { + let mut store = ResidentConversations::<&'static str>::new(policy(8, 4)); + store.publish(&toks(1, 10), "A"); + assert!(store.take_for(&toks(2, 3), |_| true).is_none()); + store.publish(&toks(2, 3), "B"); + let mut a = toks(1, 10); + a.push(1); + // The parked A fails the actor's admission: it is discarded, B (live) is parked. + assert!(store.take_for(&a, |s| *s != "A").is_none()); + assert_eq!(store.parked(), 1); + // A live session that fails admission is dropped too. + store.publish(&toks(9, 4), "C"); + let mut c = toks(9, 4); + c.push(1); + assert!(store.take_for(&c, |s| *s != "C").is_none()); + assert!(!store.has_live()); + } + + #[test] + fn publishing_nothing_or_unrepresentable_tokens_leaves_no_live_session() { + let mut store = ResidentConversations::::new(policy(8, 2)); + store.publish(&[], 1); + assert!(!store.has_live()); + store.publish(&[u32::MAX], 1); + assert!(!store.has_live()); + store.publish(&[1, 2], 1); + assert!(store.take_for(&[u32::MAX], |_| true).is_none()); + assert!( + !store.has_live(), + "an unrepresentable prompt invalidates the live session" + ); + store.publish(&[1, 2], 1); + store.clear(); + assert!(!store.has_live() && store.parked() == 0); + } + + #[test] + fn operator_settings_are_parsed_strictly() { + let p = ResidentPolicy::from_values(Some("2048"), Some("3")).unwrap(); + assert_eq!((p.budget_bytes, p.slots), (2048 << 20, 3)); + assert_eq!( + ResidentPolicy::from_values(None, None).unwrap(), + ResidentPolicy::disabled() + ); + assert!(!ResidentPolicy::disabled().enabled()); + for bad in [ + "", + "-1", + "+1", + " 1", + "1 ", + "1e3", + "0x10", + "99999999999999999999", + "٣", + ] { + assert!( + ResidentPolicy::from_values(Some(bad), None).is_err(), + "{bad:?}" + ); + assert!( + ResidentPolicy::from_values(None, Some(bad)).is_err(), + "{bad:?}" + ); + } + assert!(ResidentPolicy::from_values(None, Some("65")).is_err()); + assert!(ResidentPolicy::from_values(Some("4194305"), None).is_err()); + assert_eq!( + ResidentPolicy::from_values(Some("0"), Some("0")) + .unwrap() + .budget_bytes, + 0 + ); + } + + #[test] + fn the_accounting_estimate_saturates() { + let p = ResidentPolicy::disabled(); + assert_eq!(p.estimate(0), p.fixed_bytes); + assert_eq!( + p.estimate(100_000), + p.fixed_bytes + 100_000 * p.bytes_per_token + ); + assert_eq!(p.estimate(usize::MAX), usize::MAX); + } +}