From 117378198befeceb322eaa2517a123935f08e7f1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 22:59:48 +0100 Subject: [PATCH 1/5] STRA-338 S14: Clock port in leleka-obs and MemoryPressure port in leleka-memory Clock (SystemClock, ManualClock, AnyClock) lives in leleka_obs::time. The governor reads the host through MemoryPressure (ProcPressure over the real /proc or Win32 text, ScriptedPressure for tests) and times itself, its ledger, the telemetry window and the nvidia-smi rate limit on a Clock. Governor::new and the telemetry entry points keep their signatures. Tests: rising, falling and flapping pressure, the one-second shed step and the stale-sampler fallback on a manual clock. --- architecture-baseline.json | 3 +- crates/leleka-memory/src/governor.rs | 7 +- .../governor/impl_governor/impl_governor_2.rs | 21 +- .../governor/impl_governor/impl_governor_3.rs | 17 +- .../src/governor/pressure_tests.rs | 126 ++++++++++++ crates/leleka-memory/src/ledger.rs | 10 +- crates/leleka-memory/src/lib.rs | 2 + crates/leleka-memory/src/pressure_port.rs | 157 +++++++++++++++ crates/leleka-memory/src/smi.rs | 44 ++++- crates/leleka-memory/src/telemetry.rs | 3 + crates/leleka-memory/src/telemetry/lock.rs | 14 +- crates/leleka-memory/src/telemetry/render.rs | 71 ++++--- crates/leleka-memory/src/telemetry/tests.rs | 20 ++ crates/obs/src/time.rs | 5 +- crates/obs/src/time/clock.rs | 185 ++++++++++++++++++ 15 files changed, 630 insertions(+), 55 deletions(-) create mode 100644 crates/leleka-memory/src/governor/pressure_tests.rs create mode 100644 crates/leleka-memory/src/pressure_port.rs create mode 100644 crates/obs/src/time/clock.rs diff --git a/architecture-baseline.json b/architecture-baseline.json index fdd72ced..70e3aa48 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -173,10 +173,11 @@ "instant-now:leleka-gptoss-npu": 13, "instant-now:leleka-gpu-npu-worker": 4, "instant-now:leleka-igpu": 1, - "instant-now:leleka-memory": 12, + "instant-now:leleka-memory": 1, "instant-now:leleka-model-format": 10, "instant-now:leleka-native-cpu-expert": 30, "instant-now:leleka-npu-service": 5, + "instant-now:leleka-obs": 3, "instant-now:leleka-runtime": 42, "instant-now:strata-control": 31, "instant-now:strata-desktop-core": 15, diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index 54221107..b199677c 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -14,6 +14,8 @@ use crate::lock::{LockDecision, LockMode, LockOutcome}; use crate::lock::{plan_lock, residency_from_smaps}; use crate::plan::{GIB, MIB, Plan, Policy, Refusal, gib}; use crate::pressure::{Level, Monitor, Sample, Transition}; +use crate::pressure_port::{MemoryPressure, ProcPressure}; +use leleka_obs::time::{AnyClock, Clock}; use serde::Serialize; use serde_json::json; use std::collections::VecDeque; @@ -127,7 +129,8 @@ struct Guarded { struct Inner { cfg: GovernorConfig, - src: Arc, + src: Arc, + clock: AnyClock, epoch: Instant, plan: Mutex>, monitor: Mutex, @@ -171,6 +174,8 @@ pub struct SamplerGuard { handles: Vec>, } +#[cfg(test)] +mod pressure_tests; #[cfg(test)] mod tests; diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs index 2ba38b9f..2f18eef6 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs @@ -7,13 +7,25 @@ use super::*; impl Governor { pub fn new(cfg: GovernorConfig, src: Arc) -> Self { + Self::with_parts(cfg, ProcPressure(src), AnyClock::System) + } + + /// A governor over any [`MemoryPressure`] on the system clock. + pub fn with_pressure(cfg: GovernorConfig, pressure: impl MemoryPressure + 'static) -> Self { + Self::with_parts(cfg, pressure, AnyClock::System) + } + + /// A governor over any [`MemoryPressure`] and any clock: the composition root, and the way a test scripts both. + pub fn with_parts(cfg: GovernorConfig, pressure: impl MemoryPressure + 'static, clock: AnyClock) -> Self { let policy0 = cfg.policy; let monitor = Monitor::new(policy0); Self { inner: Arc::new(Inner { cfg, - src, - epoch: Instant::now(), + src: Arc::new(pressure), + epoch: clock.now(), + ledger: Ledger::with_clock(clock.clone()), + clock, plan: Mutex::new(None), monitor: Mutex::new(monitor), policy: Mutex::new(policy0), @@ -31,7 +43,6 @@ impl Governor { since_ms: AtomicU64::new(0), transitions: Mutex::new(VecDeque::new()), counters: Counters::default(), - ledger: Ledger::new(), vram: Mutex::new(None), post_load: Mutex::new(None), #[cfg(all(target_os = "linux", target_pointer_width = "64"))] @@ -85,13 +96,13 @@ impl Governor { &*self.inner.src } pub fn probe(&self) -> HostFacts { - HostFacts::probe(&*self.inner.src) + self.inner.src.facts() } pub fn census(&self) -> Census { Census::take(&*self.inner.src) } pub(in super::super) fn now_ms(&self) -> u64 { - self.inner.epoch.elapsed().as_millis() as u64 + self.inner.clock.since(self.inner.epoch).as_millis() as u64 } pub fn log(&self, text: &str) { if self.inner.cfg.log { diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs index c6d2e0a0..cbeca80c 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs @@ -13,7 +13,7 @@ impl Governor { /// size, and the report says so. `None` is the whole archive. #[cfg(all(target_os = "linux", target_pointer_width = "64"))] pub fn guard_archive_extents(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64, extents: Option<&[crate::lock::Span]>) -> Result { - let started = Instant::now(); + let started = self.inner.clock.now(); let facts = self.probe(); let mode = self.inner.cfg.lock_mode; if let Some(spans) = extents @@ -50,7 +50,7 @@ impl Governor { extent_bytes, memlock_soft: facts.memlock.map(|m| m.0), memlock_hard: facts.memlock.map(|m| m.1), - millis: started.elapsed().as_secs_f64() * 1e3, + millis: self.inner.clock.since(started).as_secs_f64() * 1e3, }; self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); if mode == LockMode::Require { @@ -82,7 +82,8 @@ impl Governor { let allow = |n: u64| { // a swapped-out chunk is read back into RAM: keep the hard floor + reserve let need = if swapped > 0 { n } else { 0 }; - HostFacts::probe(&*src).effective_available().is_none_or(|a| a.saturating_sub(need) >= policy.hard_floor + policy.reserve) + let floor = policy.hard_floor + policy.reserve; + src.facts().effective_available().is_none_or(|a| a.saturating_sub(need) >= floor) }; let outcome = match extents { Some(spans) => mapping.lock_ranges(spans, GIB, allow), @@ -104,7 +105,7 @@ impl Governor { extent_bytes, memlock_soft: facts.memlock.map(|m| m.0), memlock_hard: facts.memlock.map(|m| m.1), - millis: started.elapsed().as_secs_f64() * 1e3, + millis: self.inner.clock.since(started).as_secs_f64() * 1e3, }; if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { let (numbers, advice) = match &decision { @@ -133,12 +134,12 @@ impl Governor { let policy = self.policy(); let mut slot = lock(&self.inner.guarded); let Some(g) = slot.as_mut() else { return 0 }; - let started = Instant::now(); + let started = self.inner.clock.now(); let Some(text) = self.inner.src.read("/proc/self/smaps").ok() else { return 0 }; let Some(r) = residency_from_smaps(&text, g.mapping.start(), g.mapping.len()) else { return 0 }; - let read_ms = started.elapsed().as_secs_f64() * 1e3; + let read_ms = self.inner.clock.since(started).as_secs_f64() * 1e3; g.last = Some(r); - g.last_check = Some(Instant::now()); + g.last_check = Some(self.inner.clock.now()); g.last_swapped = r.swapped_bytes; if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { g.warned_swapped = r.swapped_bytes; @@ -155,7 +156,7 @@ impl Governor { } if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); - let ok = HostFacts::probe(&*self.inner.src) + let ok = self.inner.src.facts() .effective_available() .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); if ok { diff --git a/crates/leleka-memory/src/governor/pressure_tests.rs b/crates/leleka-memory/src/governor/pressure_tests.rs new file mode 100644 index 00000000..d8d25527 --- /dev/null +++ b/crates/leleka-memory/src/governor/pressure_tests.rs @@ -0,0 +1,126 @@ +//! The governor over a scripted host and a manual clock (STRA-338 S14): rising, falling and flapping pressure, the +//! once-a-second shed step and the stale-sampler fallback, with no wall-clock sleeps. + +use super::*; +use crate::pressure_port::ScriptedPressure; +use leleka_obs::time::ManualClock; + +const SHAPE: RequestShape = RequestShape { + prompt_tokens: 1000, + max_new_tokens: 100, + max_context: 262_144, +}; + +/// A governor whose host reads `available_mib` one reading per probe, on a clock that stands still. +fn scripted(available_mib: &[u64]) -> (Governor, ManualClock) { + let clock = ManualClock::new(); + let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); + cfg.log = false; + let g = Governor::with_parts( + cfg, + ScriptedPressure::available_mib(available_mib), + AnyClock::from(clock.clone()), + ); + g.set_prefix_budget(8 * GIB); + (g, clock) +} + +fn levels_after(g: &Governor, samples: u64) -> Vec { + (0..samples) + .map(|i| { + g.sample_at(1000 * (i + 1)); + g.level() + }) + .collect() +} + +#[test] +fn pressure_that_rises_steps_up_at_once_and_one_level_at_a_time_down_after_three_calm_samples() { + let mut script = vec![20_000, 3000, 1024]; + script.extend([30_000; 6]); + let (g, _clock) = scripted(&script); + let seen = levels_after(&g, script.len() as u64); + use Level::{Normal, Reject, Shed}; + assert_eq!( + seen, + [ + Normal, Shed, Reject, Reject, Reject, Shed, Shed, Shed, Normal + ] + ); + assert_eq!(g.report()["counters"]["level_changes"], 4); +} + +#[test] +fn a_host_that_flaps_around_the_soft_floor_never_steps_down() { + let script: Vec = (0..10) + .map(|i| if i % 2 == 0 { 3000 } else { 20_000 }) + .collect(); + let (g, _clock) = scripted(&script); + let seen = levels_after(&g, script.len() as u64); + assert!(seen.iter().all(|level| *level == Level::Shed), "{seen:?}"); + let report = g.report(); + assert_eq!( + report["counters"]["level_changes"], 1, + "one transition, then held: {report}" + ); + assert_eq!(report["counters"]["samples"], 10); +} + +#[test] +fn three_calm_samples_in_a_row_after_flapping_lift_the_shed() { + let (g, _clock) = scripted(&[3000, 20_000, 3000, 20_000, 20_000, 20_000]); + let seen = levels_after(&g, 6); + use Level::{Normal, Shed}; + assert_eq!(seen, [Shed, Shed, Shed, Shed, Shed, Normal]); +} + +#[test] +fn the_prefix_budget_steps_down_a_quarter_once_per_second_of_the_clock() { + let (g, clock) = scripted(&[3000]); + g.sample_at(0); + assert_eq!(g.directive(8 * GIB).prefix_budget, Some(6 * GIB)); + assert_eq!( + g.directive(6 * GIB).prefix_budget, + Some(6 * GIB), + "no second step in the same instant" + ); + clock.advance_ms(999); + assert_eq!( + g.directive(6 * GIB).prefix_budget, + Some(6 * GIB), + "999 ms is not a second" + ); + clock.advance_ms(1); + assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB / 4 * 3)); + assert_eq!(g.report()["counters"]["shed_steps"], 2); +} + +#[test] +fn the_uptime_in_the_report_is_the_clock_since_the_governor_was_built() { + let (g, clock) = scripted(&[20_000]); + assert_eq!(g.report()["uptime_ms"], 0); + clock.advance_ms(2500); + assert_eq!(g.report()["uptime_ms"], 2500); +} + +#[test] +fn a_stuck_reject_is_lifted_by_the_requests_themselves_once_the_sampler_is_five_intervals_stale() { + let mut script = vec![1024]; + script.extend([30_000; 8]); + let (g, clock) = scripted(&script); + g.sample_at(0); + assert_eq!(g.level(), Level::Reject); + let stale = Duration::from_millis(g.config().sample_interval_ms * 5 + 1); + // not stale yet: the gate stays shut and no sample is taken on the request's behalf + clock.advance(stale / 2); + assert!(matches!(g.admit(&SHAPE), Admission::Refuse(_))); + assert_eq!(g.report()["counters"]["samples"], 1); + // each stale admit takes one calm sample; the third lifts one level and the request is admitted + for _ in 0..2 { + clock.advance(stale); + assert!(matches!(g.admit(&SHAPE), Admission::Refuse(_))); + } + clock.advance(stale); + assert_eq!(g.admit(&SHAPE), Admission::Admit); + assert_eq!(g.level(), Level::Shed); +} diff --git a/crates/leleka-memory/src/ledger.rs b/crates/leleka-memory/src/ledger.rs index 8a6ac6f7..42359f4e 100644 --- a/crates/leleka-memory/src/ledger.rs +++ b/crates/leleka-memory/src/ledger.rs @@ -5,6 +5,7 @@ //! registered with the inventory (cuBLAS workspaces, graphs, the CUDA context) show up here. use crate::host::{HostFacts, ProcSource}; +use leleka_obs::time::{AnyClock, Clock}; use serde::Serialize; use std::sync::Mutex; use std::time::Instant; @@ -76,20 +77,25 @@ pub struct OpenStage { #[derive(Debug, Default)] pub struct Ledger { stages: Mutex>, + clock: AnyClock, } impl Ledger { pub fn new() -> Self { Self::default() } + /// A ledger that times its stages on `clock`. + pub fn with_clock(clock: AnyClock) -> Self { + Self { stages: Mutex::default(), clock } + } pub fn begin(&self, name: &str, src: &dyn ProcSource, device: Option) -> OpenStage { - OpenStage { name: name.to_owned(), started: Instant::now(), host: HostSample::take(src), device } + OpenStage { name: name.to_owned(), started: self.clock.now(), host: HostSample::take(src), device } } pub fn end(&self, open: OpenStage, src: &dyn ProcSource, device: Option) -> Stage { let after = HostSample::take(src); let stage = Stage { name: open.name, - millis: open.started.elapsed().as_secs_f64() * 1e3, + millis: self.clock.since(open.started).as_secs_f64() * 1e3, rss: delta(after.rss, open.host.rss), pinned: delta(after.pinned, open.host.pinned), shmem: delta(after.shmem, open.host.shmem), diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs index 49464ce6..cc0240cd 100644 --- a/crates/leleka-memory/src/lib.rs +++ b/crates/leleka-memory/src/lib.rs @@ -14,6 +14,7 @@ pub mod ledger; pub mod lock; pub mod plan; pub mod pressure; +pub mod pressure_port; pub mod procfs; pub mod smi; pub mod telemetry; @@ -24,3 +25,4 @@ pub use host::{FakeProc, HostFacts, ProcSource, RealProc}; pub use inventory::{Entry, Inventory, Space, When}; pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram}; pub use pressure::Level; +pub use pressure_port::{MemoryPressure, ProcPressure, ScriptedPressure}; diff --git a/crates/leleka-memory/src/pressure_port.rs b/crates/leleka-memory/src/pressure_port.rs new file mode 100644 index 00000000..71b0e78b --- /dev/null +++ b/crates/leleka-memory/src/pressure_port.rs @@ -0,0 +1,157 @@ +//! The port the governor reads host memory through (STRA-338 S14). +//! +//! [`MemoryPressure`] answers "what does the host say about memory right now?" as one [`HostFacts`] reading, from +//! which the governor takes the available bytes, PSI, the cgroup event counters and the swap-out counter that feed the +//! [`crate::pressure::Monitor`]. It is also a [`ProcSource`], because the residency guard and the census still read +//! single files (`/proc/self/smaps`) through the same object. +//! +//! * [`ProcPressure`] is the adapter for production: `/proc` and `/sys` on Linux, the Win32 text renderings of +//! `winproc.rs` on Windows, parsed by [`HostFacts::probe`] exactly as before. +//! * [`ScriptedPressure`] is the fixture: a list of readings handed out one per probe, the last one repeating, so a +//! test can play a rising, falling or flapping host without touching the real one. +use crate::host::{FakeProc, HostFacts, ProcSource}; +use std::io; +use std::sync::Mutex; + +/// One reading of the host per call. +pub trait MemoryPressure: ProcSource + Send + Sync { + /// The host facts now. + fn facts(&self) -> HostFacts; +} + +impl ProcSource for std::sync::Arc { + fn read(&self, path: &str) -> io::Result { + (**self).read(path) + } + fn count_entries(&self, path: &str) -> io::Result { + (**self).count_entries(path) + } +} + +/// The real host, read through a [`ProcSource`] (`RealProc` in production). +#[derive(Clone, Copy, Debug, Default)] +pub struct ProcPressure(pub S); + +impl ProcSource for ProcPressure { + fn read(&self, path: &str) -> io::Result { + self.0.read(path) + } + fn count_entries(&self, path: &str) -> io::Result { + self.0.count_entries(path) + } +} + +impl MemoryPressure for ProcPressure { + fn facts(&self) -> HostFacts { + HostFacts::probe(&self.0) + } +} + +/// A scripted host: reading `n` of the script is the answer of probe `n`; past the end the last one repeats. +#[derive(Debug)] +pub struct ScriptedPressure { + script: Vec, + state: Mutex, +} + +impl ScriptedPressure { + /// A script of ready readings (at least one). + pub fn new(script: Vec) -> Self { + assert!( + !script.is_empty(), + "a scripted host needs at least one reading" + ); + Self { + script, + state: Mutex::new(0), + } + } + + /// A script of hosts that differ only in `MemAvailable`, in MiB, with 121 GiB in total and no swap. + pub fn available_mib(readings: &[u64]) -> Self { + Self::new( + readings + .iter() + .map(|mib| host_with_available(*mib)) + .collect(), + ) + } + + /// How many times the host was probed. + pub fn probes(&self) -> usize { + *self.state.lock().unwrap_or_else(|p| p.into_inner()) + } +} + +fn host_with_available(mib: u64) -> HostFacts { + let meminfo = format!( + "MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", + 121 * 1024 * 1024, + mib * 1024 + ); + let status = "VmRSS: 1000 kB\nThreads: 3\n"; + HostFacts::probe( + &FakeProc::default() + .with("/proc/meminfo", &meminfo) + .with("/proc/self/status", status), + ) +} + +impl ProcSource for ScriptedPressure { + fn read(&self, path: &str) -> io::Result { + Err(io::Error::new(io::ErrorKind::NotFound, path.to_owned())) + } + fn count_entries(&self, path: &str) -> io::Result { + Err(io::Error::new(io::ErrorKind::NotFound, path.to_owned())) + } +} + +impl MemoryPressure for ScriptedPressure { + fn facts(&self) -> HostFacts { + let mut next = self.state.lock().unwrap_or_else(|p| p.into_inner()); + let facts = self.script[(*next).min(self.script.len() - 1)].clone(); + *next += 1; + facts + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host::RealProc; + + #[test] + fn the_script_plays_in_order_and_repeats_its_last_reading() { + let host = ScriptedPressure::available_mib(&[8000, 2000]); + let seen: Vec<_> = (0..4).map(|_| host.facts().effective_available()).collect(); + assert_eq!( + seen, + [ + Some(8000 << 20), + Some(2000 << 20), + Some(2000 << 20), + Some(2000 << 20) + ] + ); + assert_eq!(host.probes(), 4); + } + + #[test] + fn a_scripted_host_has_no_files_so_file_based_facts_read_as_unknown() { + let host = ScriptedPressure::available_mib(&[1]); + assert!(host.read("/proc/self/smaps").is_err()); + assert!(host.count_entries("/proc/self/fd").is_err()); + } + + #[test] + fn the_real_adapter_probes_through_its_source() { + let fake = FakeProc::default().with( + "/proc/meminfo", + "MemTotal: 2048 kB\nMemAvailable: 1024 kB\n", + ); + let pressure = ProcPressure(fake); + assert_eq!(pressure.facts().effective_available(), Some(1024 << 10)); + assert_eq!(pressure.facts(), HostFacts::probe(&pressure)); + let _real: ProcPressure = ProcPressure::default(); + } +} diff --git a/crates/leleka-memory/src/smi.rs b/crates/leleka-memory/src/smi.rs index 2a6aac21..2c51e16a 100644 --- a/crates/leleka-memory/src/smi.rs +++ b/crates/leleka-memory/src/smi.rs @@ -7,6 +7,7 @@ //! [`RUN_LIMIT`]. The parser is a pure function over the CSV text and is unit-tested on real output samples, including //! the `[N/A]` and `[Not Supported]` placeholders. use crate::telemetry::GpuSample; +use leleka_obs::time::{Clock, SystemClock}; use std::{ io::Read, process::{Command, Stdio}, @@ -116,18 +117,27 @@ pub fn probe(index: u32) -> Option Option + Send + Sy /// [`probe`] over a given binary. pub fn probe_with(binary: std::path::PathBuf, index: u32) -> Box Option + Send + Sync> { + Box::new(probe_with_clock(binary, index, SystemClock)) +} + +/// [`probe_with`] whose rate limit is judged on `clock`. +pub fn probe_with_clock( + binary: std::path::PathBuf, + index: u32, + clock: impl Clock + Send + Sync + 'static, +) -> impl Fn() -> Option + Send + Sync { let last: Mutex)>> = Mutex::new(None); - Box::new(move || { + move || { let mut last = last.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); if let Some((at, sample)) = last.as_ref() - && at.elapsed() < MIN_INTERVAL + && clock.since(*at) < MIN_INTERVAL { return sample.clone(); } let sample = query(&binary, index); - *last = Some((Instant::now(), sample.clone())); + *last = Some((clock.now(), sample.clone())); sample - }) + } } #[cfg(test)] @@ -225,4 +235,30 @@ mod tests { assert_eq!(query(&failing, 0), None); let _ = std::fs::remove_dir_all(&dir); } + #[cfg(unix)] + #[test] + fn the_probe_asks_again_only_after_the_clock_passes_the_interval() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("leleka-smi-clock-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let counter = dir.join("calls"); + let script = dir.join("nvidia-smi"); + let body = format!("#!/bin/sh +echo x >> {} +echo '0, 55, 20, 2048, 8192, 75.5, 1800, 50, Test GPU' +", counter.display()); + std::fs::write(&script, body).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + let clock = leleka_obs::time::ManualClock::new(); + let probe = probe_with_clock(script, 0, clock.clone()); + let runs = || std::fs::read_to_string(&counter).map_or(0, |text| text.lines().count()); + assert!(probe().is_some()); + clock.advance(MIN_INTERVAL - Duration::from_millis(1)); + assert!(probe().is_some()); + assert_eq!(runs(), 1, "inside the interval the last answer is reused"); + clock.advance_ms(1); + assert!(probe().is_some()); + assert_eq!(runs(), 2, "at the interval the device is asked again"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/leleka-memory/src/telemetry.rs b/crates/leleka-memory/src/telemetry.rs index 8ccd64c6..36057696 100644 --- a/crates/leleka-memory/src/telemetry.rs +++ b/crates/leleka-memory/src/telemetry.rs @@ -9,6 +9,7 @@ use crate::{ host::{ProcSource, RealProc}, procfs, }; +use leleka_obs::time::{Clock, SystemClock}; use serde::Serialize; use std::{ sync::{ @@ -252,6 +253,8 @@ struct Document { /// Everything the sampler measured this tick. pub struct Measured { + /// The monotonic reading this tick was taken at; the request clocks of the document are measured against it. + pub at: Instant, pub now_ms: u64, pub uptime_s: u64, pub gpu: Option, diff --git a/crates/leleka-memory/src/telemetry/lock.rs b/crates/leleka-memory/src/telemetry/lock.rs index dc2a2f41..b8a31249 100644 --- a/crates/leleka-memory/src/telemetry/lock.rs +++ b/crates/leleka-memory/src/telemetry/lock.rs @@ -29,9 +29,14 @@ pub fn set_context_max(tokens: u64) { /// A request entered the engine with `prompt_tokens` in its prompt (the cache hit is known when it finishes; the figures of the last finished request stay until then). pub fn request_started(prompt_tokens: u64) { + request_started_at(prompt_tokens, SystemClock.now()); +} + +/// [`request_started`] with the instant the request entered the engine, read by the caller from its own clock. +pub fn request_started_at(prompt_tokens: u64, at: Instant) { with_state(|s| { s.phase = Phase::Prefill; - s.started = Some(Instant::now()); + s.started = Some(at); s.first_token = None; s.produced_now = 0; s.prompt_now = prompt_tokens; @@ -41,9 +46,14 @@ pub fn request_started(prompt_tokens: u64) { /// Tokens were delivered: the first delivery ends the prefill phase. pub fn tokens_delivered(count: u64) { + tokens_delivered_at(count, SystemClock.now()); +} + +/// [`tokens_delivered`] with the instant of the delivery, read by the caller from its own clock. +pub fn tokens_delivered_at(count: u64, at: Instant) { with_state(|s| { if s.first_token.is_none() { - s.first_token = Some(Instant::now()); + s.first_token = Some(at); s.phase = Phase::Decode; } s.produced_now += count; diff --git a/crates/leleka-memory/src/telemetry/render.rs b/crates/leleka-memory/src/telemetry/render.rs index 2ee901a9..bbb4f8e7 100644 --- a/crates/leleka-memory/src/telemetry/render.rs +++ b/crates/leleka-memory/src/telemetry/render.rs @@ -15,7 +15,7 @@ pub(super) fn render(state: &State, measured: &Measured) -> String { }); let live_rate = match (state.phase, state.first_token) { (Phase::Decode, Some(first)) if state.produced_now > 1 => { - let secs = first.elapsed().as_secs_f64(); + let secs = measured.at.saturating_duration_since(first).as_secs_f64(); (secs > 0.05).then(|| round1(state.produced_now as f64 / secs)) } _ => None, @@ -28,7 +28,7 @@ pub(super) fn render(state: &State, measured: &Measured) -> String { request: state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest { prompt_tokens: state.prompt_now, generated_tokens: state.produced_now, - elapsed_s: (started.elapsed().as_secs_f64() * 10.0).round() / 10.0, + elapsed_s: (measured.at.saturating_duration_since(started).as_secs_f64() * 10.0).round() / 10.0, }), gpu: measured.gpu.clone(), ram, @@ -100,39 +100,48 @@ impl Drop for Sampler { /// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU block. pub fn start(gpu_probe: Option, period: Duration) -> Sampler { + start_with_clock(gpu_probe, period, SystemClock) +} + +/// [`start`] with the monotonic readings of every tick taken from `clock`. +pub fn start_with_clock(gpu_probe: Option, period: Duration, clock: impl Clock + Send + 'static) -> Sampler { let stop = Arc::new(AtomicBool::new(false)); let flag = stop.clone(); - let spawned = std::thread::Builder::new().name("leleka-telemetry".into()).spawn(move || { - let src = RealProc; - let began = Instant::now(); - let cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); - let mut previous = read_cpu(&src).map(|reading| (reading, Instant::now())); - while !flag.load(Ordering::Acquire) { - std::thread::sleep(period); - let now = Instant::now(); - let reading = read_cpu(&src); - let cpu = match (&previous, &reading) { - (Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))), - _ => None, - }; - if let Some(reading) = reading { - previous = Some((reading, now)); - } - let measured = Measured { - now_ms: SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64), - uptime_s: began.elapsed().as_secs(), - gpu: gpu_probe.as_ref().and_then(|probe| probe()), - meminfo: procfs::parse_meminfo(&src.read("/proc/meminfo").unwrap_or_default()), - status: procfs::parse_status(&src.read("/proc/self/status").unwrap_or_default()), - cores, - cpu, - }; - let text = render_now(&measured); - *lock(&PUBLISHED) = Some(text); - } - }); + let spawned = std::thread::Builder::new() + .name("leleka-telemetry".into()) + .spawn(move || sample_until_stopped(&flag, gpu_probe, period, &clock)); if spawned.is_err() { stop.store(true, Ordering::Release); } Sampler { stop } } + +fn sample_until_stopped(flag: &AtomicBool, gpu_probe: Option, period: Duration, clock: &impl Clock) { + let src = RealProc; + let began = clock.now(); + let cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32); + let mut previous = read_cpu(&src).map(|reading| (reading, clock.now())); + while !flag.load(Ordering::Acquire) { + std::thread::sleep(period); + let now = clock.now(); + let reading = read_cpu(&src); + let cpu = match (&previous, &reading) { + (Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))), + _ => None, + }; + if let Some(reading) = reading { + previous = Some((reading, now)); + } + let measured = Measured { + at: now, + now_ms: SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64), + uptime_s: now.saturating_duration_since(began).as_secs(), + gpu: gpu_probe.as_ref().and_then(|probe| probe()), + meminfo: procfs::parse_meminfo(&src.read("/proc/meminfo").unwrap_or_default()), + status: procfs::parse_status(&src.read("/proc/self/status").unwrap_or_default()), + cores, + cpu, + }; + *lock(&PUBLISHED) = Some(render_now(&measured)); + } +} diff --git a/crates/leleka-memory/src/telemetry/tests.rs b/crates/leleka-memory/src/telemetry/tests.rs index f22f7285..4def72d0 100644 --- a/crates/leleka-memory/src/telemetry/tests.rs +++ b/crates/leleka-memory/src/telemetry/tests.rs @@ -6,6 +6,7 @@ static SERIAL: Mutex<()> = Mutex::new(()); fn measured() -> Measured { Measured { + at: Instant::now(), now_ms: 1, uptime_s: 5, gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900), temp_c: Some(61), name: Some("NVIDIA GeForce RTX 5090".into()), ..Default::default() }), @@ -176,3 +177,22 @@ fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() { assert!(doc["cache"]["hit_ratio"].is_null()); assert!(doc["context"]["used_pct"].is_null()); } + +#[test] +fn the_in_flight_clocks_follow_the_instants_the_caller_read() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + let clock = leleka_obs::time::ManualClock::new(); + request_started_at(5_000, clock.now()); + clock.advance_ms(2000); + tokens_delivered_at(3, clock.now()); + clock.advance_ms(1000); + tokens_delivered_at(10, clock.now()); + clock.advance_ms(2000); + let tick = Measured { at: clock.now(), ..measured() }; + let doc: serde_json::Value = serde_json::from_str(&render_now(&tick)).unwrap(); + assert_eq!(doc["request"]["elapsed_s"], 5.0); + // 13 tokens since the first delivery, 3 s after it + assert_eq!(doc["throughput"]["decode_tok_s_live"], 4.3); + *lock(&STATE) = None; +} diff --git a/crates/obs/src/time.rs b/crates/obs/src/time.rs index 14982c8e..44b31c1f 100644 --- a/crates/obs/src/time.rs +++ b/crates/obs/src/time.rs @@ -1,6 +1,9 @@ -//! UTC timestamps without a date library (days-from-civil, Howard Hinnant). +//! UTC timestamps without a date library (days-from-civil, Howard Hinnant), and the monotonic [`Clock`] port. use std::time::{SystemTime, UNIX_EPOCH}; +mod clock; +pub use clock::{AnyClock, Clock, ManualClock, SystemClock}; + /// Milliseconds since the Unix epoch. pub fn now_ms() -> u64 { SystemTime::now() diff --git a/crates/obs/src/time/clock.rs b/crates/obs/src/time/clock.rs new file mode 100644 index 00000000..5a391ce7 --- /dev/null +++ b/crates/obs/src/time/clock.rs @@ -0,0 +1,185 @@ +//! Monotonic time as a port (STRA-338 S14). +//! +//! Decision code that has a deadline, a window or an accounting period reads time through [`Clock`] instead of calling +//! `Instant::now()`. [`SystemClock`] is the adapter for production (zero-sized, one `Instant::now()`); [`ManualClock`] +//! is the fixture for tests: it moves only when the test says so. The reading is a plain [`Instant`], so a value read +//! from either clock can be stored, compared and passed on without a conversion. +//! +//! Use it at coarse points (a request, an admission decision, a sampling tick). Hot loops (per token, per layer, per +//! kernel) take the reading once and compare it themselves; a struct that holds a clock is generic over it with +//! [`SystemClock`] as the default, so nothing is boxed and nothing is dispatched dynamically. [`AnyClock`] is for the +//! rare owner that cannot be generic (a process-wide singleton). +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +/// A source of monotonic readings. +pub trait Clock { + /// The current reading. + fn now(&self) -> Instant; + + /// Time since `earlier`, zero when `earlier` is in the future. + fn since(&self, earlier: Instant) -> Duration { + self.now().saturating_duration_since(earlier) + } +} + +impl Clock for &C { + fn now(&self) -> Instant { + (**self).now() + } +} + +/// The operating system's monotonic clock. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SystemClock; + +impl Clock for SystemClock { + #[inline] + fn now(&self) -> Instant { + Instant::now() + } +} + +/// A clock that only moves when told to; clones share one timeline. A [`Self::ticking`] clock also moves by a fixed +/// step after every reading, which makes a polling loop with a deadline finish in a known number of rounds. +#[derive(Clone, Debug)] +pub struct ManualClock { + base: Instant, + advanced_ns: Arc, + tick_ns: u64, +} + +impl ManualClock { + /// A clock standing at an arbitrary starting point. + pub fn new() -> Self { + Self { + base: Instant::now(), + advanced_ns: Arc::new(AtomicU64::new(0)), + tick_ns: 0, + } + } + + /// A clock that moves forward by `step` after each reading. + pub fn ticking(step: Duration) -> Self { + Self { + tick_ns: u64::try_from(step.as_nanos()).unwrap_or(u64::MAX), + ..Self::new() + } + } + + /// Move every clone of this clock forward. + pub fn advance(&self, by: Duration) { + let ns = u64::try_from(by.as_nanos()).unwrap_or(u64::MAX); + self.advanced_ns.fetch_add(ns, Ordering::AcqRel); + } + + /// [`Self::advance`] in milliseconds. + pub fn advance_ms(&self, ms: u64) { + self.advance(Duration::from_millis(ms)); + } +} + +impl Default for ManualClock { + fn default() -> Self { + Self::new() + } +} + +impl Clock for ManualClock { + fn now(&self) -> Instant { + self.base + Duration::from_nanos(self.advanced_ns.fetch_add(self.tick_ns, Ordering::AcqRel)) + } +} + +/// One of the two clocks, for an owner that must not be generic. +#[derive(Clone, Debug, Default)] +pub enum AnyClock { + #[default] + System, + Manual(ManualClock), +} + +impl Clock for AnyClock { + fn now(&self) -> Instant { + match self { + Self::System => Instant::now(), + Self::Manual(clock) => clock.now(), + } + } +} + +impl From for AnyClock { + fn from(clock: ManualClock) -> Self { + Self::Manual(clock) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_manual_clock_stands_still_until_advanced() { + let clock = ManualClock::new(); + let first = clock.now(); + assert_eq!(clock.now(), first); + clock.advance_ms(1500); + assert_eq!(clock.now() - first, Duration::from_millis(1500)); + assert_eq!(clock.since(first), Duration::from_millis(1500)); + } + + #[test] + fn clones_share_one_timeline_and_since_never_underflows() { + let clock = ManualClock::new(); + let other = clock.clone(); + let start = clock.now(); + other.advance(Duration::from_secs(3)); + assert_eq!(clock.since(start), Duration::from_secs(3)); + assert_eq!(start.checked_duration_since(clock.now()), None); + assert_eq!( + clock.since(clock.now() + Duration::from_secs(1)), + Duration::ZERO + ); + } + + #[test] + fn a_ticking_clock_moves_by_its_step_after_every_reading() { + let clock = ManualClock::ticking(Duration::from_secs(2)); + let first = clock.now(); + assert_eq!(clock.now() - first, Duration::from_secs(2)); + assert_eq!(clock.since(first), Duration::from_secs(4)); + clock.advance_ms(500); + assert_eq!(clock.now() - first, Duration::from_millis(6500)); + } + + #[test] + fn the_system_clock_is_monotonic_and_zero_sized() { + let clock = SystemClock; + let a = clock.now(); + let b = clock.now(); + assert!(b >= a); + assert_eq!(std::mem::size_of::(), 0); + } + + #[test] + fn any_clock_follows_the_clock_it_wraps() { + let manual = ManualClock::new(); + let any = AnyClock::from(manual.clone()); + let start = any.now(); + manual.advance_ms(40); + assert_eq!(any.since(start), Duration::from_millis(40)); + assert!(AnyClock::default().since(Instant::now()) < Duration::from_secs(1)); + } + + #[test] + fn a_reference_to_a_clock_is_a_clock() { + fn elapsed(clock: impl Clock, start: Instant) -> Duration { + clock.since(start) + } + let manual = ManualClock::new(); + let start = manual.now(); + manual.advance_ms(7); + assert_eq!(elapsed(&manual, start), Duration::from_millis(7)); + } +} From 1d94c7b378b50e7250ff54376350b3f41febde52 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 23:21:04 +0100 Subject: [PATCH 2/5] STRA-338 S14: request, sweep and retention timing read an injected Clock in leleka-runtime Generation (generate, generate_mtp), the terminal and event publication, the source verification, the measurement recorder, the Original serve loop (request deadline, idle sweep, reconfigure), the TTFT marks, the seed plan, the prefix device phases and the prefix cache (retention scale and phase timers, now per cache instead of a process OnceLock) take a Clock; the composition roots hand them SystemClock. emit_event is one function in utf8.rs instead of two copies. Hot loops keep comparing against the reading taken at the start of the request. Tests on a manual clock: terminal and event backpressure limits, prefill/decode accounting, source verification reads, the idle sweep cadence and the prefix retention. --- architecture-baseline.json | 6 +- crates/leleka-runtime/src/backend.rs | 3 + .../leleka-runtime/src/backend/clock_tests.rs | 154 ++++++++++++++++++ crates/leleka-runtime/src/backend/generate.rs | 44 ++--- .../src/backend/generate_mtp.rs | 18 +- crates/leleka-runtime/src/backend/load.rs | 2 + .../leleka-runtime/src/backend/load_cuda.rs | 1 + .../src/backend/load_sources.rs | 2 +- crates/leleka-runtime/src/backend/owner.rs | 1 + .../src/backend/serve_generate.rs | 5 +- .../leleka-runtime/src/backend/serve_run.rs | 12 +- crates/leleka-runtime/src/backend/sources.rs | 12 +- crates/leleka-runtime/src/backend/utf8.rs | 31 +++- .../leleka-runtime/src/backend_measurement.rs | 18 +- .../src/backend_original_serve.rs | 77 ++++----- .../src/gpu_proofs/combined_prefix_numeric.rs | 4 +- .../gpu_proofs/native_down_candidate_only.rs | 6 +- .../src/gpu_proofs/native_down_public_pair.rs | 6 +- crates/leleka-runtime/src/idle_sweep.rs | 63 +++++++ crates/leleka-runtime/src/lib.rs | 1 + .../src/qwen_forward/original_serve_prefix.rs | 10 +- .../original_serve_prefix/clock_tests.rs | 68 ++++++++ .../impl_prefixconfig.rs | 6 - .../impl_prefixserve/impl_prefixserve_2.rs | 31 +++- .../impl_prefixserve/impl_prefixserve_2_2.rs | 18 +- .../original_serve_prefix/tests.rs | 14 +- .../src/qwen_forward/original_serve_stack.rs | 3 + .../impl_default_for_ttftmarks.rs | 9 +- .../impl_originalservestack_2.rs | 3 +- .../impl_originalservestack_2_2.rs | 2 +- .../impl_originalservestack_4.rs | 8 +- .../impl_originalservestack_5.rs | 6 +- ...mpl_prefixdevice_for_originalservestack.rs | 12 +- 33 files changed, 491 insertions(+), 165 deletions(-) create mode 100644 crates/leleka-runtime/src/backend/clock_tests.rs create mode 100644 crates/leleka-runtime/src/idle_sweep.rs create mode 100644 crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs diff --git a/architecture-baseline.json b/architecture-baseline.json index 70e3aa48..e67dff2a 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -78,7 +78,7 @@ "crates/igpu/src/lib.rs": 1386, "crates/igpu/src/shaders.rs": 440, "crates/leleka-memory/src/lock.rs": 432, - "crates/leleka-runtime/src/backend_original_serve.rs": 1130, + "crates/leleka-runtime/src/backend_original_serve.rs": 1113, "crates/leleka-runtime/src/conversation/cache/tests.rs": 407, "crates/leleka-runtime/src/conversation/manager_tests.rs": 1129, "crates/leleka-runtime/src/conversation/snapshot_tests.rs": 1596, @@ -178,7 +178,7 @@ "instant-now:leleka-native-cpu-expert": 30, "instant-now:leleka-npu-service": 5, "instant-now:leleka-obs": 3, - "instant-now:leleka-runtime": 42, + "instant-now:leleka-runtime": 17, "instant-now:strata-control": 31, "instant-now:strata-desktop-core": 15, "path-include:leleka-cuda-driver": 115, @@ -194,7 +194,7 @@ "process-global:leleka-model-format": 8, "process-global:leleka-native-cpu-expert": 32, "process-global:leleka-obs": 7, - "process-global:leleka-runtime": 61, + "process-global:leleka-runtime": 59, "process-global:leleka-tokenizer": 4, "process-global:strata-control": 14 } diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 9c0ce81b..6dae1e2b 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -37,6 +37,7 @@ use leleka_backend_api::{ ModelDescriptor, RecentIds, RuntimeConfig, SupportedModelTuple, Usage, }; use leleka_cuda_driver::Driver; +use leleka_obs::time::{Clock, SystemClock}; use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; use leleka_tokenizer::Tokenizer; pub use measurement::{ @@ -117,6 +118,8 @@ use utf8::*; mod errors; use errors::*; +#[cfg(test)] +mod clock_tests; #[cfg(test)] mod tests; diff --git a/crates/leleka-runtime/src/backend/clock_tests.rs b/crates/leleka-runtime/src/backend/clock_tests.rs new file mode 100644 index 00000000..013d57f6 --- /dev/null +++ b/crates/leleka-runtime/src/backend/clock_tests.rs @@ -0,0 +1,154 @@ +//! The request clocks of the backend on a manual clock (STRA-338 S14): the terminal publication deadline, the +//! prefill/decode accounting of the measurement recorder and the clock reads of the source verification. + +use super::*; +use leleka_obs::time::ManualClock; + +fn completed() -> GenerationTerminal { + GenerationTerminal::Completed { + reason: FinishReason::Stop, + usage: Usage { + input_tokens: 1, + output_tokens: 1, + reused_input_tokens: 0, + }, + } +} + +fn filler() -> GenerationEvent { + GenerationEvent::TextDelta { text: "x".into() } +} + +#[test] +fn a_terminal_with_room_is_published_after_one_clock_read() { + let (sink, mut stream) = GenerationSink::bounded_channel(2).unwrap(); + let clock = ManualClock::ticking(Duration::from_secs(10)); + let before = clock.now(); + assert!(emit_terminal(&sink, completed(), &clock).is_ok()); + // the clock moved once for the publication and once for the reading below + assert_eq!(clock.now() - before, Duration::from_secs(20)); + assert!(matches!( + stream.recv(), + Ok(Some(GenerationEvent::Terminal(_))) + )); +} + +#[test] +fn a_terminal_that_meets_a_full_queue_gives_up_when_the_clock_passes_the_backpressure_limit() { + let (sink, _stream) = GenerationSink::bounded_channel(1).unwrap(); + sink.try_emit(filler()).unwrap(); + // 10 s per reading: the start (0), then 10 s and 20 s are inside the 30 s limit, 30 s is not + let clock = ManualClock::ticking(BACKPRESSURE_TIMEOUT / 3); + let result = emit_terminal(&sink, completed(), &clock); + assert!( + matches!(result, Err(ContractError::GenerationBackpressure)), + "{result:?}" + ); +} + +#[test] +fn a_terminal_waits_while_the_clock_stands_inside_the_limit_and_goes_through_when_the_reader_frees_a_slot() + { + let (sink, mut stream) = GenerationSink::bounded_channel(1).unwrap(); + sink.try_emit(filler()).unwrap(); + let clock = ManualClock::new(); + let reader = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(30)); + let first = stream.recv(); + let second = stream.recv(); + (first, second) + }); + // the clock never moves, so only the reader can end the wait + assert!(emit_terminal(&sink, completed(), &clock).is_ok()); + let (first, second) = reader.join().unwrap(); + assert!(matches!(first, Ok(Some(GenerationEvent::TextDelta { .. })))); + assert!(matches!(second, Ok(Some(GenerationEvent::Terminal(_))))); +} + +#[test] +fn an_event_that_meets_a_full_queue_gives_up_at_the_backpressure_limit_but_a_cancel_wins_first() { + let (sink, _stream) = GenerationSink::bounded_channel(1).unwrap(); + sink.try_emit(filler()).unwrap(); + let clock = ManualClock::ticking(BACKPRESSURE_TIMEOUT / 3); + let result = emit_event(&sink, &|| false, &clock, filler()); + assert!( + matches!(result, Err(GenerationFailure::Backend(_))), + "the limit is a backend refusal" + ); + let rounds = std::cell::Cell::new(0); + let cancel_on_second = || { + rounds.set(rounds.get() + 1); + rounds.get() >= 2 + }; + let slow = ManualClock::new(); + let result = emit_event(&sink, &cancel_on_second, &slow, filler()); + assert!(matches!(result, Err(GenerationFailure::Cancelled))); + assert_eq!( + rounds.get(), + 2, + "one wait of 5 ms on a clock that never reaches the limit, then the cancel" + ); +} + +fn finished_request(clock: &ManualClock, prefill_ms: u64, decode_ms: u64) -> EvaluationMeasurement { + let mut record = measurement::Recorder::with_clock(&[4, 5, 4], 1, clock.clone()); + clock.advance_ms(prefill_ms); + record.prefilled(); + record.token(7); + clock.advance_ms(decode_ms); + record.decoded(); + let counts = measurement::CacheCounts { + expert_hits: 0, + expert_misses: 0, + expert_source_bytes: 0, + expert_upload_bytes: 0, + expert_eviction_bytes: 0, + dense_hits: 0, + dense_source_bytes: 0, + dense_upload_bytes: 0, + }; + record + .finish(counts, counts, true, true, true, Some((3, 1, 0))) + .expect("complete record") +} + +#[test] +fn the_recorder_measures_prefill_from_its_start_and_decode_from_the_end_of_prefill() { + let clock = ManualClock::new(); + let measured = finished_request(&clock, 120, 300); + assert_eq!(measured.prefill, Duration::from_millis(120)); + assert_eq!(measured.decode, Duration::from_millis(300)); +} + +#[test] +fn two_recorders_on_one_clock_do_not_see_each_others_start() { + let clock = ManualClock::new(); + clock.advance_ms(5000); + let measured = finished_request(&clock, 7, 11); + assert_eq!( + (measured.prefill, measured.decode), + (Duration::from_millis(7), Duration::from_millis(11)) + ); +} + +#[test] +fn source_verification_reads_the_clock_once_per_phase_and_reports_missing_files_as_refusals() { + let config = NativeBackendConfig { + shard0: "absent-shard0.gguf".into(), + shard1: "absent-shard1.gguf".into(), + gpu_device_ordinal: 0, + gpu_budget_bytes: 0, + context_tokens: 0, + kar_ple_source: None, + kar_ple_inherited: None, + mtp_source: None, + kar_expert_source: None, + experimental: Default::default(), + }; + let clock = ManualClock::ticking(Duration::from_secs(1)); + let before = clock.now(); + let sources = verify_sources_parallel(&config, false, &clock); + assert!(sources.shard0.is_err() && sources.shard1.is_err() && sources.kar.is_none()); + // the wall of the whole step, shard 1 and shard 0: three readings, plus the one below + assert_eq!(clock.now() - before, Duration::from_secs(4)); +} diff --git a/crates/leleka-runtime/src/backend/generate.rs b/crates/leleka-runtime/src/backend/generate.rs index da05d727..8aff0474 100644 --- a/crates/leleka-runtime/src/backend/generate.rs +++ b/crates/leleka-runtime/src/backend/generate.rs @@ -1,7 +1,7 @@ //! The single-token generation step loop. use super::*; -pub(super) struct Generation<'a, 'context, 'driver> { +pub(super) struct Generation<'a, 'context, 'driver, C: Clock = SystemClock> { pub(super) execution: EvaluationExecution, pub(super) measurement: Option<&'a std::cell::RefCell>, pub(super) binding: &'a ModelBinding, @@ -19,6 +19,8 @@ pub(super) struct Generation<'a, 'context, 'driver> { pub(super) context_tokens: u32, pub(super) eos: u32, pub(super) mtp: bool, + /// Read once per request or tile, never per kernel; the deadline checks compare against that reading. + pub(super) clock: C, } pub(super) enum GenerationFailure { Cancelled, @@ -29,7 +31,7 @@ impl From for GenerationFailure { Self::Backend(error) } } -impl Generation<'_, '_, '_> { +impl Generation<'_, '_, '_, C> { pub(super) fn observe(&self, f: impl FnOnce(&mut measurement::Recorder)) { if let Some(recorder) = self.measurement { f(&mut recorder.borrow_mut()); @@ -168,7 +170,7 @@ impl Generation<'_, '_, '_> { if self.cancelled() { return Err(GenerationFailure::Cancelled); } - if started.elapsed() > GENERATION_TIMEOUT { + if self.clock.since(started) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } if tokens.is_empty() || tokens.len() > self.prefill_tile_cap() { @@ -193,11 +195,12 @@ impl Generation<'_, '_, '_> { let cancel = self.cancel; let shared = self.shared; let sink = self.sink; + let clock = &self.clock; let stopped = || { cancel.load(Ordering::Acquire) || shared.shutdown.load(Ordering::Acquire) || sink.is_closed() - || started.elapsed() > GENERATION_TIMEOUT + || clock.since(started) > GENERATION_TIMEOUT }; // This is an incremental transaction cap, not an unbounded host pool. // Verified model and already committed KV/cache owners stay outside it. @@ -235,7 +238,7 @@ impl Generation<'_, '_, '_> { Err(crate::qwen_forward::contract::Error::Unsupported( crate::qwen_forward::contract::Stage::Executor, )) if stopped() => { - if started.elapsed() > GENERATION_TIMEOUT { + if self.clock.since(started) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } return Err(GenerationFailure::Cancelled); @@ -248,40 +251,21 @@ impl Generation<'_, '_, '_> { Ok(product) } pub(super) fn emit(&self, event: GenerationEvent) -> Result<(), GenerationFailure> { - let start = Instant::now(); - loop { - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - match self.sink.try_emit(event.clone()) { - Ok(()) => return Ok(()), - Err(ContractError::GenerationBackpressure) - if start.elapsed() < BACKPRESSURE_TIMEOUT => - { - thread::sleep(Duration::from_millis(5)) - } - Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled), - _ => { - return Err( - exhausted("generation output backpressure deadline exceeded").into(), - ); - } - } - } + emit_event(self.sink, &|| self.cancelled(), &self.clock, event) } } -pub(super) fn generate( - mut run: Generation<'_, '_, '_>, +pub(super) fn generate( + mut run: Generation<'_, '_, '_, C>, prompt: &[u32], max: u32, ) -> Result<(FinishReason, Usage), GenerationFailure> { if run.mtp { return generate_mtp(run, prompt, max); } - let start = Instant::now(); + let start = run.clock.now(); let mut next = 0; for (position, &token) in prompt.iter().enumerate() { - if start.elapsed() > GENERATION_TIMEOUT { + if run.clock.since(start) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } next = run.step(token, position)?; @@ -290,7 +274,7 @@ pub(super) fn generate( let mut utf8 = Utf8Pending::default(); let mut count = 0; for index in 0..max { - if start.elapsed() > GENERATION_TIMEOUT { + if run.clock.since(start) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } if run.cancelled() { diff --git a/crates/leleka-runtime/src/backend/generate_mtp.rs b/crates/leleka-runtime/src/backend/generate_mtp.rs index 57230eb3..5b5a873b 100644 --- a/crates/leleka-runtime/src/backend/generate_mtp.rs +++ b/crates/leleka-runtime/src/backend/generate_mtp.rs @@ -1,23 +1,23 @@ //! The MTP speculative generation loop. use super::*; -pub(super) fn generate_mtp( - run: Generation<'_, '_, '_>, +pub(super) fn generate_mtp( + run: Generation<'_, '_, '_, C>, prompt: &[u32], max: u32, ) -> Result<(FinishReason, Usage), GenerationFailure> { generate_mtp_resume(run, prompt, max, None, &mut None) } -pub(super) fn generate_mtp_resume( - mut run: Generation<'_, '_, '_>, +pub(super) fn generate_mtp_resume( + mut run: Generation<'_, '_, '_, C>, prompt: &[u32], max: u32, resume: Option, publish: &mut Option, ) -> Result<(FinishReason, Usage), GenerationFailure> { *publish = None; - let start = Instant::now(); + let start = run.clock.now(); let (mut decoder, mut latest, reused, mut committed) = match resume { Some(old) => { if !append_compatible(&old.tokens, prompt) { @@ -81,7 +81,7 @@ pub(super) fn generate_mtp_resume( let adaptive_prefill = false; let mut position = reused; while position < prompt.len() { - if start.elapsed() > GENERATION_TIMEOUT { + if run.clock.since(start) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } let mut end = position @@ -119,7 +119,7 @@ pub(super) fn generate_mtp_resume( let mut utf8 = Utf8Pending::default(); let mut count = 0_u64; let reason = loop { - if start.elapsed() > GENERATION_TIMEOUT { + if run.clock.since(start) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } if run.cancelled() { @@ -177,11 +177,11 @@ pub(super) fn generate_mtp_resume( cancel.load(Ordering::Acquire) || shared.shutdown.load(Ordering::Acquire) || sink.is_closed() - || start.elapsed() > GENERATION_TIMEOUT + || run.clock.since(start) > GENERATION_TIMEOUT }, ) .map_err(|e| match e { - MtpWindowError::Cancelled if start.elapsed() > GENERATION_TIMEOUT => { + MtpWindowError::Cancelled if run.clock.since(start) > GENERATION_TIMEOUT => { GenerationFailure::Backend(unavailable("generation deadline exceeded")) } MtpWindowError::Cancelled => GenerationFailure::Cancelled, diff --git a/crates/leleka-runtime/src/backend/load.rs b/crates/leleka-runtime/src/backend/load.rs index ef6f405a..b36dcdf9 100644 --- a/crates/leleka-runtime/src/backend/load.rs +++ b/crates/leleka-runtime/src/backend/load.rs @@ -17,6 +17,8 @@ pub(super) struct LoadEnv<'a> { pub(super) optimized: Option<&'a OptimizedBackendConfig>, pub(super) original: Option<&'a original_serve::OriginalServeOptions>, pub(super) settings: &'a crate::settings::Settings, + /// The time of this load and of every request it serves; the composition root picks the type. + pub(super) clock: SystemClock, } pub(super) fn serve_load( diff --git a/crates/leleka-runtime/src/backend/load_cuda.rs b/crates/leleka-runtime/src/backend/load_cuda.rs index b6289582..a61b78d8 100644 --- a/crates/leleka-runtime/src/backend/load_cuda.rs +++ b/crates/leleka-runtime/src/backend/load_cuda.rs @@ -106,6 +106,7 @@ pub(super) fn launch_original<'d>( reply: env.reply, options, model_files: vec![env.config.shard0.clone(), env.config.shard1.clone()], + clock: env.clock, }) } #[cfg(not(all( diff --git a/crates/leleka-runtime/src/backend/load_sources.rs b/crates/leleka-runtime/src/backend/load_sources.rs index c72a0aaf..d1adf878 100644 --- a/crates/leleka-runtime/src/backend/load_sources.rs +++ b/crates/leleka-runtime/src/backend/load_sources.rs @@ -25,7 +25,7 @@ pub(super) fn open_sources( let parallel_sources = !flags.resident_owners && !flags.streamed_spill; let archive_wanted = kar_mtp_requested(requested); let mut prefetched = - parallel_sources.then(|| verify_sources_parallel(env.config, archive_wanted)); + parallel_sources.then(|| verify_sources_parallel(env.config, archive_wanted, &env.clock)); let (shard0, capture) = open_shard0(env.config, prefetched.as_mut(), flags).map_err(shard0_refusal)?; crate::load_clock::lap("shard0_result"); diff --git a/crates/leleka-runtime/src/backend/owner.rs b/crates/leleka-runtime/src/backend/owner.rs index a4636fdb..6b90a078 100644 --- a/crates/leleka-runtime/src/backend/owner.rs +++ b/crates/leleka-runtime/src/backend/owner.rs @@ -122,6 +122,7 @@ impl<'a> OwnerCtx<'a> { optimized: self.selection.optimized.as_ref(), original: self.selection.original.as_ref(), settings: crate::settings::process(), + clock: SystemClock, }; if let Err(error) = serve_load(&env, model, requested) { let _ = reply.send(Err(error)); diff --git a/crates/leleka-runtime/src/backend/serve_generate.rs b/crates/leleka-runtime/src/backend/serve_generate.rs index 00f8365c..16d08aa8 100644 --- a/crates/leleka-runtime/src/backend/serve_generate.rs +++ b/crates/leleka-runtime/src/backend/serve_generate.rs @@ -50,9 +50,10 @@ impl<'c> Exchange<'c> { ) -> Self { let before = Counters::of(sv.weights); let measured = sv.env.observer.map(|_| { - RefCell::new(measurement::Recorder::new( + RefCell::new(measurement::Recorder::with_clock( &admitted.prompt, job.request.max_output_tokens, + sv.env.clock, )) }); Self { @@ -194,7 +195,7 @@ fn conclude( let shared = sv.env.shared; // Terminal publication is bounded too; after transport loss, // closing without a terminal is reported as MissingTerminal. - let published = emit_terminal(&admitted.sink, terminal_of(outcome)).is_ok(); + let published = emit_terminal(&admitted.sink, terminal_of(outcome), &sv.env.clock).is_ok(); let continuation = terminal_admit( x.pending_prefix.take(), verdict.stopped, diff --git a/crates/leleka-runtime/src/backend/serve_run.rs b/crates/leleka-runtime/src/backend/serve_run.rs index 01779258..0969568d 100644 --- a/crates/leleka-runtime/src/backend/serve_run.rs +++ b/crates/leleka-runtime/src/backend/serve_run.rs @@ -24,14 +24,17 @@ pub(super) fn run_generation<'c>( ) } +/// The session of the exchange and the recorder that observes it, when there is one. +type RunParts<'a, 'c> = ( + &'a mut QwenSession<'c>, + Option<&'a RefCell>, +); + pub(super) fn build_run<'a, 'c, 'd>( sv: &'a mut Serving<'_, 'c, 'd>, job: &'a Job, admitted: &'a Admitted, - (session, measurement): ( - &'a mut QwenSession<'c>, - Option<&'a RefCell>, - ), + (session, measurement): RunParts<'a, 'c>, ) -> Generation<'a, 'c, 'd> { Generation { measurement, @@ -52,6 +55,7 @@ pub(super) fn build_run<'a, 'c, 'd>( sv.loaded.effective_mode, InferenceMode::ExperimentalMtp { .. } ), + clock: sv.env.clock, } } diff --git a/crates/leleka-runtime/src/backend/sources.rs b/crates/leleka-runtime/src/backend/sources.rs index 8e97afc9..516a998c 100644 --- a/crates/leleka-runtime/src/backend/sources.rs +++ b/crates/leleka-runtime/src/backend/sources.rs @@ -20,12 +20,12 @@ pub(super) type InputResultKar = pub(super) fn verify_sources_parallel( config: &NativeBackendConfig, want_kar: bool, + clock: &(impl Clock + Sync), ) -> VerifiedSources { - use std::time::Instant; - let begun = Instant::now(); + let begun = clock.now(); let result = std::thread::scope(|scope| { let shard1 = scope.spawn(|| { - let started = Instant::now(); + let started = clock.now(); let result = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|e| e.to_string()); crate::load_clock::span("shard1_sha256_and_index", started); result @@ -36,7 +36,7 @@ pub(super) fn verify_sources_parallel( .filter(|_| want_kar) .map(|archive| { scope.spawn(move || { - let started = Instant::now(); + let started = clock.now(); let result = crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive( archive, @@ -45,7 +45,7 @@ pub(super) fn verify_sources_parallel( result }) }); - let started = Instant::now(); + let started = clock.now(); let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0).map_err(|e| e.to_string()); crate::load_clock::span("shard0_sha256_and_index", started); VerifiedSources { @@ -65,7 +65,7 @@ pub(super) fn verify_sources_parallel( /// It uses exactly the functions of `serve_load`, so what it measures is what a start spends. pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendError> { crate::load_clock::begin(); - let sources = verify_sources_parallel(&config, true); + let sources = verify_sources_parallel(&config, true, &SystemClock); sources .shard0 .map_err(|_| invalid("pinned shard 0 verification failed"))?; diff --git a/crates/leleka-runtime/src/backend/utf8.rs b/crates/leleka-runtime/src/backend/utf8.rs index ae8055db..b7875643 100644 --- a/crates/leleka-runtime/src/backend/utf8.rs +++ b/crates/leleka-runtime/src/backend/utf8.rs @@ -59,12 +59,13 @@ impl Utf8Pending { pub(super) fn emit_terminal( sink: &GenerationSink, terminal: GenerationTerminal, + clock: &impl Clock, ) -> Result<(), ContractError> { - let start = Instant::now(); + let start = clock.now(); loop { match sink.try_emit(GenerationEvent::Terminal(terminal.clone())) { Err(ContractError::GenerationBackpressure) - if start.elapsed() < BACKPRESSURE_TIMEOUT => + if clock.since(start) < BACKPRESSURE_TIMEOUT => { thread::sleep(Duration::from_millis(5)) } @@ -72,3 +73,29 @@ pub(super) fn emit_terminal( } } } + +/// Publish one event: wait for room in the stream for at most the backpressure limit, give up at once when `cancelled` +/// says so or the reader is gone. +pub(super) fn emit_event( + sink: &GenerationSink, + cancelled: &dyn Fn() -> bool, + clock: &impl Clock, + event: GenerationEvent, +) -> Result<(), GenerationFailure> { + let start = clock.now(); + loop { + if cancelled() { + return Err(GenerationFailure::Cancelled); + } + match sink.try_emit(event.clone()) { + Ok(()) => return Ok(()), + Err(ContractError::GenerationBackpressure) + if clock.since(start) < BACKPRESSURE_TIMEOUT => + { + thread::sleep(Duration::from_millis(5)) + } + Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled), + _ => return Err(exhausted("generation output backpressure deadline exceeded").into()), + } + } +} diff --git a/crates/leleka-runtime/src/backend_measurement.rs b/crates/leleka-runtime/src/backend_measurement.rs index 383a8fc9..60f886f2 100644 --- a/crates/leleka-runtime/src/backend_measurement.rs +++ b/crates/leleka-runtime/src/backend_measurement.rs @@ -1,4 +1,5 @@ //! Explicit public-evaluation owner only. No logging, RPC, or normal-serving observer. +use leleka_obs::time::{Clock, SystemClock}; use std::{ sync::Arc, time::{Duration, Instant}, @@ -52,10 +53,11 @@ pub struct EvaluationMeasurement { pub stopped: bool, pub terminal_published: bool, } -pub(super) struct Recorder { +pub(super) struct Recorder { input: Vec, output: Vec, windows: Vec, + clock: C, start: Instant, prefill: Option, decode: Option, @@ -64,12 +66,20 @@ pub(super) struct Recorder { failed: Option, } impl Recorder { + #[cfg(test)] pub(super) fn new(input: &[u32], max: u32) -> Self { + Self::with_clock(input, max, SystemClock) + } +} +impl Recorder { + /// A recorder whose prefill and decode durations are measured on `clock`. + pub(super) fn with_clock(input: &[u32], max: u32, clock: C) -> Self { let mut this = Self { input: Vec::new(), output: Vec::new(), windows: Vec::new(), - start: Instant::now(), + start: clock.now(), + clock, prefill: None, decode: None, retained: 0, @@ -102,7 +112,7 @@ impl Recorder { } } pub(super) fn prefilled(&mut self) { - if self.prefill.replace(self.start.elapsed()).is_some() { + if self.prefill.replace(self.clock.since(self.start)).is_some() { self.failed = Some(MeasurementFailure::Incomplete) } } @@ -143,7 +153,7 @@ impl Recorder { pub(super) fn decoded(&mut self) { self.decode = self .prefill - .and_then(|p| self.start.elapsed().checked_sub(p)); + .and_then(|p| self.clock.since(self.start).checked_sub(p)); } pub(super) fn finish( self, diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index ac1c0c49..380f607a 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -294,12 +294,13 @@ pub(super) use runner::{run, Run}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod runner { use super::super::{ - emit_terminal, exhausted, invalid, load_failure, prepare_prompt, request_sampler, clock_seed, unavailable, - ActiveGuard, BackendError, Command, ContractError, ErrorCode, FinishReason, GenerationEvent, + emit_event, emit_terminal, exhausted, invalid, load_failure, prepare_prompt, request_sampler, clock_seed, unavailable, + ActiveGuard, BackendError, Command, ErrorCode, FinishReason, GenerationEvent, GenerationFailure, GenerationSink, GenerationTerminal, LoadPhase, LoadedModel, ModelBinding, Reply, Shared, - Tokenizer, Usage, Utf8Pending, BACKPRESSURE_TIMEOUT, GENERATION_TIMEOUT, QUEUE, + Tokenizer, Usage, Utf8Pending, GENERATION_TIMEOUT, QUEUE, }; use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY}; + use crate::idle_sweep::IdleSweep; type GpuProbe = Box Option + Send + Sync>; @@ -335,6 +336,7 @@ mod runner { original_serve_verifier::ServeFailure, }; use leleka_backend_api::GenerationRequest; + use leleka_obs::time::{Clock, SystemClock}; use std::{ path::PathBuf, rc::Rc, @@ -343,7 +345,7 @@ mod runner { mpsc::{self, Receiver}, }, thread, - time::{Duration, Instant}, + time::Duration, }; /// Everything the Original owner loop needs from `serve_load` once the context exists. @@ -360,6 +362,7 @@ mod runner { pub(in super::super) options: &'a OriginalServeOptions, /// The model files, for the start-up report only (size and mtime are read; the content never is). pub(in super::super) model_files: Vec, + pub(in super::super) clock: SystemClock, } /// Host memory a reconfigure needs beside the soft floor: the reopened stack's pinned K/V (3.1 GiB at 262,144 cells), rings and pools. @@ -466,27 +469,6 @@ mod runner { } } - fn emit_event( - sink: &GenerationSink, - cancelled: &dyn Fn() -> bool, - event: GenerationEvent, - ) -> Result<(), GenerationFailure> { - let start = Instant::now(); - loop { - if cancelled() { - return Err(GenerationFailure::Cancelled); - } - match sink.try_emit(event.clone()) { - Ok(()) => return Ok(()), - Err(ContractError::GenerationBackpressure) if start.elapsed() < BACKPRESSURE_TIMEOUT => { - thread::sleep(Duration::from_millis(5)) - } - Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled), - _ => return Err(exhausted("generation output backpressure deadline exceeded").into()), - } - } - } - fn admission_error(admission: Admission) -> BackendError { match admission { Admission::Context => exhausted("prompt and output exceed configured context"), @@ -607,6 +589,7 @@ mod runner { prompt: &[u32], request: &GenerationRequest, spec_min_p: f32, + clock: &impl Clock, ) -> Result<(FinishReason, Usage), GenerationFailure> { let sampler = request_sampler(request, clock_seed()).map_err(|_| invalid("unsupported generation request"))?; let serve_request = ServeRequest::new( @@ -619,17 +602,17 @@ mod runner { ); let stop_tokens = crate::qwen_forward::original_serve_request::original_stop_tokens(eos); let cancelled = || cancel.load(Ordering::Acquire) || shared.shutdown.load(Ordering::Acquire) || sink.is_closed(); - let start = Instant::now(); + let start = clock.now(); let mut utf8 = Utf8Pending::default(); let mut count: u64 = 0; let mut captured: Option = None; let mut timed_out = false; let mut generated_ids: Vec = Vec::new(); - leleka_memory::telemetry::request_started(prompt.len() as u64); + leleka_memory::telemetry::request_started_at(prompt.len() as u64, start); let result = { let mut emit = |tokens: &[i32]| -> Result<(), ForwardError> { generated_ids.extend_from_slice(tokens); - leleka_memory::telemetry::tokens_delivered(tokens.len() as u64); + leleka_memory::telemetry::tokens_delivered_at(tokens.len() as u64, clock.now()); let mut deliver = |token: i32| -> Result<(), GenerationFailure> { count += 1; if stop_tokens.contains(&token) { @@ -640,7 +623,7 @@ mod runner { .decode_bytes(&[token as u32]) .map_err(|_| unavailable("native token decoding failed"))?; if let Some(text) = utf8.push(&bytes)? { - emit_event(sink, &cancelled, GenerationEvent::TextDelta { text })?; + emit_event(sink, &cancelled, clock, GenerationEvent::TextDelta { text })?; } Ok(()) }; @@ -653,7 +636,7 @@ mod runner { Ok(()) }; let mut cancel_probe = || { - if start.elapsed() > GENERATION_TIMEOUT { + if clock.since(start) > GENERATION_TIMEOUT { timed_out = true; return true; } @@ -700,7 +683,7 @@ mod runner { ServeStop::Length | ServeStop::Context => FinishReason::Length, }; if matches!(reason, FinishReason::Length) { - utf8.finish_length(|text| emit_event(sink, &cancelled, GenerationEvent::TextDelta { text }))?; + utf8.finish_length(|text| emit_event(sink, &cancelled, clock, GenerationEvent::TextDelta { text }))?; } else { utf8.finish()?; } @@ -721,7 +704,7 @@ mod runner { swaps: s.swaps, }); leleka_memory::telemetry::request_detail(&request.request_id, outcome.rounds as u64, tier); - emit_event(sink, &cancelled, GenerationEvent::Usage(usage.clone()))?; + emit_event(sink, &cancelled, clock, GenerationEvent::Usage(usage.clone()))?; log_request_end(&request.request_id, &usage, prompt_ms, decode_ms, outcome.produced as u64, outcome.rounds as u64, tier); if leleka_obs::settings().legacy { // the exact lines scripts/e2e/analyze_session.py parses @@ -744,7 +727,7 @@ mod runner { /// Open the stack, answer the load, then serve commands until unload/shutdown. Returns the unload reply /// target, as `serve_load` does after its loop. pub(in super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError> { - let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files } = args; + let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files, clock } = args; // the settings can change at run time (`Command::Reconfigure`): this thread owns the current copy let mut options = options.clone(); let mut context_tokens = context_tokens; @@ -810,20 +793,19 @@ mod runner { return Ok(()); } let mut unload_reply = None; - let mut last_sweep = Instant::now(); + let mut sweep = IdleSweep::new(Duration::from_secs(15), &clock); while !shared.shutdown.load(Ordering::Acquire) { match rx.recv_timeout(Duration::from_millis(100)) { Err(mpsc::RecvTimeoutError::Timeout) => { // sessions idle past the retention time give their host memory back - if last_sweep.elapsed() >= Duration::from_secs(15) { - last_sweep = Instant::now(); - if let Some(owner) = stack.as_mut() { - let expired = owner.prefix_expire_idle(); - if expired > 0 { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve prefix retention: expired {expired} idle checkpoint(s); {}", owner.prefix_metrics().unwrap_or_default()); - publish_prefix_summary(owner, shared); - } + if sweep.due(&clock) + && let Some(owner) = stack.as_mut() + { + let expired = owner.prefix_expire_idle(); + if expired > 0 { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve prefix retention: expired {expired} idle checkpoint(s); {}", owner.prefix_metrics().unwrap_or_default()); + publish_prefix_summary(owner, shared); } } continue; @@ -860,7 +842,7 @@ mod runner { } } let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure: {changed:?}; reopening the serve stack"); - let started = Instant::now(); + let started = clock.now(); shared.ready.store(false, Ordering::Release); if let Some(old) = stack.take() { if old.close().is_err() { @@ -914,7 +896,7 @@ mod runner { leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); let effective = crate::serve_tuning::describe(&options, context_tokens, workers, None); leleka_memory::telemetry::set_settings(effective.clone()); - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure done in {:.1} s", started.elapsed().as_secs_f64()); + let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure done in {:.1} s", clock.since(started).as_secs_f64()); Ok(effective.to_string()) })(); let _ = reply.send(outcome); @@ -978,10 +960,11 @@ mod runner { message: "Original serve stack is not available".into(), retryable: false, }, + &clock, ); continue; }; - let result = generate(owner, &tokenizer, &sink, &cancel, shared, eos, &prompt, &request, options.spec_min_p); + let result = generate(owner, &tokenizer, &sink, &cancel, shared, eos, &prompt, &request, options.spec_min_p, &clock); let terminal = match result { Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage }, Err(GenerationFailure::Cancelled) => GenerationTerminal::Cancelled, @@ -991,7 +974,7 @@ mod runner { retryable: false, }, }; - let _ = emit_terminal(&sink, terminal); + let _ = emit_terminal(&sink, terminal, &clock); publish_prefix_summary(owner, shared); if let Some(lost) = owner.health() { // a lost physical owner cannot be repaired in place: stop serving, keep the process diff --git a/crates/leleka-runtime/src/gpu_proofs/combined_prefix_numeric.rs b/crates/leleka-runtime/src/gpu_proofs/combined_prefix_numeric.rs index f65cc26c..3cd8af65 100644 --- a/crates/leleka-runtime/src/gpu_proofs/combined_prefix_numeric.rs +++ b/crates/leleka-runtime/src/gpu_proofs/combined_prefix_numeric.rs @@ -119,7 +119,7 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { shared: &self.shared, context_tokens: 128, eos: self.eos, - mtp: true, + mtp: true, clock: SystemClock, }; let vocabulary = Dimension::new(248320).expect("reference vocabulary refused"); let mut decoder = MtpDecoder::new(self.binding).expect("reference draft refused"); @@ -183,7 +183,7 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { shared: &self.shared, context_tokens: 128, eos: self.eos, - mtp: true, + mtp: true, clock: SystemClock, }, prompt, 1, diff --git a/crates/leleka-runtime/src/gpu_proofs/native_down_candidate_only.rs b/crates/leleka-runtime/src/gpu_proofs/native_down_candidate_only.rs index 17c1f821..a2696ca7 100644 --- a/crates/leleka-runtime/src/gpu_proofs/native_down_candidate_only.rs +++ b/crates/leleka-runtime/src/gpu_proofs/native_down_candidate_only.rs @@ -222,7 +222,7 @@ impl Inputs<'_, '_, '_> { shared: &self.shared, context_tokens: 262144, eos: self.eos, - mtp: true, + mtp: true, clock: SystemClock, }, ids, req.max_output_tokens, @@ -241,7 +241,7 @@ impl Inputs<'_, '_, '_> { }, }; let diagnostic = format!("{terminal:?}"); - let published = emit_terminal(&sink, terminal.clone()).is_ok(); + let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); drop(sink); let joined = drain.join(); let consumer_failed = joined.is_err(); @@ -262,7 +262,7 @@ impl Inputs<'_, '_, '_> { reason: reason.clone(), usage: usage.clone(), }; - let published = emit_terminal(&sink, terminal.clone()).is_ok(); + let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); drop(sink); let (text, seen_usage, seen_terminal, first_text_at) = drain.join().expect("actual pair consumer failed"); diff --git a/crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs b/crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs index 9231aca8..6cdc4737 100644 --- a/crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs +++ b/crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs @@ -216,7 +216,7 @@ impl Inputs<'_, '_, '_> { shared: &self.shared, context_tokens: 262144, eos: self.eos, - mtp: true, + mtp: true, clock: SystemClock, }, ids, req.max_output_tokens, @@ -235,7 +235,7 @@ impl Inputs<'_, '_, '_> { }, }; let diagnostic = format!("{terminal:?}"); - let published = emit_terminal(&sink, terminal.clone()).is_ok(); + let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); drop(sink); let joined = drain.join(); let consumer_failed = joined.is_err(); @@ -255,7 +255,7 @@ impl Inputs<'_, '_, '_> { reason: reason.clone(), usage: usage.clone(), }; - let published = emit_terminal(&sink, terminal.clone()).is_ok(); + let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); drop(sink); let (text, seen_usage, seen_terminal) = drain.join().expect("actual pair consumer failed"); assert!(published && seen_terminal.as_ref() == Some(&terminal)); diff --git a/crates/leleka-runtime/src/idle_sweep.rs b/crates/leleka-runtime/src/idle_sweep.rs new file mode 100644 index 00000000..5ed65086 --- /dev/null +++ b/crates/leleka-runtime/src/idle_sweep.rs @@ -0,0 +1,63 @@ +//! The period of the idle loop's housekeeping (STRA-338 S14). +//! +//! The serve loop wakes every 100 ms to look for a command; between commands it expires the sessions nobody has used +//! for the retention time, but not on every wake-up. [`IdleSweep`] is that decision on its own: it reads the clock +//! it is handed, so the cadence is tested without waiting. +use leleka_obs::time::Clock; +use std::time::{Duration, Instant}; + +/// "Is it time to sweep again?", with the period measured from the last sweep that was due. +#[derive(Clone, Copy, Debug)] +pub(crate) struct IdleSweep { + every: Duration, + last: Instant, +} + +impl IdleSweep { + /// A sweep that is first due `every` after `clock`'s present reading. + pub(crate) fn new(every: Duration, clock: &impl Clock) -> Self { + Self { + every, + last: clock.now(), + } + } + + /// True when `every` has passed since the last due sweep (or since `new`); the next period then starts now. + pub(crate) fn due(&mut self, clock: &impl Clock) -> bool { + let now = clock.now(); + let due = now.saturating_duration_since(self.last) >= self.every; + if due { + self.last = now; + } + due + } +} + +#[cfg(test)] +mod tests { + use super::*; + use leleka_obs::time::ManualClock; + + #[test] + fn a_sweep_is_due_once_per_period_and_the_period_restarts_when_it_fires() { + let clock = ManualClock::new(); + let mut sweep = IdleSweep::new(Duration::from_secs(15), &clock); + assert!(!sweep.due(&clock), "not at the start"); + clock.advance_ms(14_999); + assert!(!sweep.due(&clock), "a millisecond early"); + clock.advance_ms(1); + assert!(sweep.due(&clock), "exactly at the period"); + assert!(!sweep.due(&clock), "the period restarted"); + clock.advance_ms(15_000); + assert!(sweep.due(&clock)); + } + + #[test] + fn a_long_gap_gives_one_sweep_not_a_burst() { + let clock = ManualClock::new(); + let mut sweep = IdleSweep::new(Duration::from_secs(15), &clock); + clock.advance(Duration::from_secs(600)); + assert!(sweep.due(&clock)); + assert!(!sweep.due(&clock)); + } +} diff --git a/crates/leleka-runtime/src/lib.rs b/crates/leleka-runtime/src/lib.rs index 79cc5509..6a0f07f2 100644 --- a/crates/leleka-runtime/src/lib.rs +++ b/crates/leleka-runtime/src/lib.rs @@ -19,6 +19,7 @@ macro_rules! bringup_trace { } pub(crate) use bringup_trace; +pub(crate) mod idle_sweep; pub(crate) mod load_clock; pub(crate) mod settings; pub mod backend; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs index ce6912cf..536900b2 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs @@ -21,6 +21,7 @@ use super::super::contract::Error; use crate::prefix_cache::{ budget, fingerprint, ByteSize, Consider, PolicyParams, PrefixMatch, PrefixStore, PrefixSummary, Reject, Stats, StoreConfig, }; +use leleka_obs::time::{AnyClock, Clock}; use std::time::Instant; /// What the operator asked for (`--prefix-cache-mib`, `--prefix-cache-block`). @@ -151,19 +152,24 @@ pub(super) struct PrefixServe { shed: bool, /// Why the last checkpoint attempt was not taken, with the numbers (read once by the stack for its log line). note: Option, + /// The retention clock of the store (milliseconds since `epoch`) and the timers of the request phases. + clock: AnyClock, + epoch: Instant, } #[cfg(test)] #[path = "original_serve_prefix/tests.rs"] mod tests; +#[cfg(test)] +#[path = "original_serve_prefix/clock_tests.rs"] +mod clock_tests; + #[path = "original_serve_prefix/impl_prefixconfig.rs"] mod impl_prefixconfig; #[allow(unused_imports)] use impl_prefixconfig::admission_reading; #[allow(unused_imports)] -use impl_prefixconfig::wall_ms; -#[allow(unused_imports)] use impl_prefixconfig::lcp; #[path = "original_serve_prefix/impl_prefixserve.rs"] mod impl_prefixserve; diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs new file mode 100644 index 00000000..200ed2bc --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs @@ -0,0 +1,68 @@ +//! The retention clock of the prefix cache on a manual clock (STRA-338 S14). + +use super::tests::{Fake, G, cfg, request}; +use super::*; +use leleka_obs::time::ManualClock; + +/// The retention clock is the one the cache was built with (STRA-338 S14): a session survives exactly its retention. +#[test] +fn idle_checkpoints_expire_when_the_clock_passes_the_retention_and_not_before() { + let clock = ManualClock::new(); + let mut s = + PrefixServe::with_clock(cfg(), 1024, 1 << 30, "test", AnyClock::from(clock.clone())); + let retention = cfg().policy.retention_ms; + assert!( + retention > 0, + "the default policy retains sessions for a finite time" + ); + let mut d = Fake::new(); + let prompt: Vec = (0..(3 * G + 10) as i32).collect(); + request(&mut s, &mut d, &prompt, None); + let nodes = s.store().node_count(); + assert!(nodes > 0, "the request left checkpoints"); + clock.advance_ms(retention); + assert_eq!( + s.expire_idle(), + 0, + "at exactly the retention the session is still kept" + ); + assert_eq!(s.store().node_count(), nodes); + clock.advance_ms(1); + assert_eq!( + s.expire_idle(), + nodes, + "one millisecond past it every idle node goes" + ); + assert_eq!(s.store().node_count(), 0); +} + +#[test] +fn a_request_renews_the_retention_of_the_checkpoints_it_used() { + let clock = ManualClock::new(); + let mut s = + PrefixServe::with_clock(cfg(), 1024, 1 << 30, "test", AnyClock::from(clock.clone())); + let retention = cfg().policy.retention_ms; + let mut d = Fake::new(); + let prompt: Vec = (0..(3 * G + 10) as i32).collect(); + request(&mut s, &mut d, &prompt, None); + clock.advance_ms(retention - 1); + let (start, _) = request(&mut s, &mut d, &prompt, None); + assert!( + start.is_some(), + "the second request resumed from a checkpoint" + ); + // the first request's other nodes are now older than the retention, the ones the second request used are not + clock.advance_ms(retention - 1); + s.expire_idle(); + let kept = s.store().node_count(); + assert!( + kept > 0, + "the checkpoints the second request used outlive the first request's retention" + ); + clock.advance_ms(2); + assert_eq!( + s.expire_idle(), + kept, + "and go when their own retention is over" + ); +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs index cd06fd2b..798ec489 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixconfig.rs @@ -62,12 +62,6 @@ pub(super) fn admission_reading(reading: Option, additional: u64, floor: u6 } } -/// Milliseconds since the first call, on the monotonic clock (the store's wall-time scale for session retention). -pub(super) fn wall_ms() -> u64 { - static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); - EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 -} - pub(super) fn lcp(a: &[i32], b: &[i32]) -> usize { a.iter().zip(b).take_while(|(x, y)| x == y).count() } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs index 242294f8..6f278cee 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs @@ -8,7 +8,19 @@ use super::*; impl PrefixServe { /// `identity`: whatever makes two runtimes' caches interchangeable (model digest, KV format...), hashed with the /// block size into the summary's namespace. + #[cfg(test)] pub(in super::super::super) fn new(cfg: PrefixConfig, capacity: usize, budget_bytes: u64, identity: &str) -> Self { + Self::with_clock(cfg, capacity, budget_bytes, identity, AnyClock::System) + } + + /// [`Self::new`] with the clock of the retention scale and the phase timers. + pub(in super::super::super) fn with_clock( + cfg: PrefixConfig, + capacity: usize, + budget_bytes: u64, + identity: &str, + clock: AnyClock, + ) -> Self { let block_tokens = cfg.resolved_block(capacity); let namespace = fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION)); let store = PrefixStore::new(StoreConfig { @@ -35,9 +47,16 @@ impl PrefixServe { configured_budget: usize::try_from(budget_bytes).unwrap_or(usize::MAX), shed: false, note: None, + epoch: clock.now(), + clock, } } + /// Milliseconds since this cache was built, on its clock (the store's wall-time scale for session retention). + pub(in super::super::super) fn wall_ms(&self) -> u64 { + self.clock.since(self.epoch).as_millis() as u64 + } + /// Apply the memory governor's shed directive (`Governor::directive`): `Some(bytes)` evicts down to that budget (lowest /// expected-value-per-byte first), `None` restores the configured one after a shed. Returns the bytes evicted. pub(in super::super::super) fn apply_shed(&mut self, target: Option, governor: &leleka_memory::Governor) -> usize { @@ -146,12 +165,12 @@ impl PrefixServe { self.req = None; return Ok(None); } - self.store.tick_at(prompt.len(), wall_ms()); + self.store.tick_at(prompt.len(), self.wall_ms()); let limit = prompt.len().saturating_sub(1); self.req = Some(Req { limit, last_grid: limit / g * g }); - let lookup = Instant::now(); + let lookup = self.clock.now(); let found = self.store.longest_match(prompt, limit); - let match_us = lookup.elapsed().as_secs_f64() * 1e6; + let match_us = self.clock.since(lookup).as_secs_f64() * 1e6; let Some(hit) = found else { self.store.record_miss(); self.last_match_us = match_us; @@ -170,7 +189,7 @@ impl PrefixServe { let branch = self.store.is_branch_point(hit.key); let common = common_full.min(hit.tokens); let copy = common < hit.tokens; - let started = Instant::now(); + let started = self.clock.now(); let full = hit.tokens / g; let first_block = (common / g).min(full); let mut blocks = if copy { self.store.blocks_from(hit.key, first_block).ok_or(Error::IdentityMismatch)? } else { Vec::new() }; @@ -184,10 +203,10 @@ impl PrefixServe { // the import overwrites every cell from the first named block on self.live.truncate(if blocks.is_empty() { common } else { first_block * g }); device.import(state, &blocks)?; - let imported_ms = started.elapsed().as_secs_f64() * 1e3; + let imported_ms = self.clock.since(started).as_secs_f64() * 1e3; device.restore_draft(state, hit.tokens)?; let copied_tokens: usize = blocks.iter().map(|(j, _)| if *j < full { g } else { hit.tokens - full * g }).sum(); - let import_ms = started.elapsed().as_secs_f64() * 1e3; + let import_ms = self.clock.since(started).as_secs_f64() * 1e3; self.last_import_split = (imported_ms, import_ms - imported_ms); self.live.clear(); self.live.extend_from_slice(&prompt[..hit.tokens]); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs index 3e2aad5e..10b80ccb 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs @@ -34,9 +34,9 @@ impl PrefixServe { let (est_state, est_block) = device.estimate(g); let est_state = self.seen_state_bytes.unwrap_or(est_state); let est_block = self.seen_block_bytes.unwrap_or(est_block); - let considering = Instant::now(); + let considering = self.clock.now(); let verdict = self.store.consider(&prompt[..end], frontier, est_state, est_block); - self.consider_ms_request += considering.elapsed().as_secs_f64() * 1e3; + self.consider_ms_request += self.clock.since(considering).as_secs_f64() * 1e3; let candidate = match verdict { Consider::Exists => return Ok(ChunkOutcome::Exists), Consider::Rejected(why) => { @@ -57,7 +57,7 @@ impl PrefixServe { )); return Ok(ChunkOutcome::LowMemory); } - let started = Instant::now(); + let started = self.clock.now(); let state = device.park_state()?; if device.position()? != end as u64 { return Err(Error::IdentityMismatch); @@ -72,7 +72,7 @@ impl PrefixServe { } let new_blocks = blocks.len(); let bytes = state.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); - let park_ms = started.elapsed().as_secs_f64() * 1e3; + let park_ms = self.clock.since(started).as_secs_f64() * 1e3; self.store.commit(candidate, &prompt[..end], state, blocks).map_err(|_| Error::IdentityMismatch)?; self.park_ms_request += park_ms; self.admitted_request += 1; @@ -126,9 +126,9 @@ impl PrefixServe { let (est_state, est_block) = device.estimate(g); let est_state = self.seen_state_bytes.unwrap_or(est_state); let est_block = self.seen_block_bytes.unwrap_or(est_block); - let considering = Instant::now(); + let considering = self.clock.now(); let verdict = self.store.consider_tail(tokens, true, est_state, est_block); - self.consider_ms_request += considering.elapsed().as_secs_f64() * 1e3; + self.consider_ms_request += self.clock.since(considering).as_secs_f64() * 1e3; let candidate = match verdict { Consider::Exists => { self.note = Some(format!("a checkpoint at {} tokens exists already", tokens.len())); @@ -157,7 +157,7 @@ impl PrefixServe { )); return Ok(ChunkOutcome::LowMemory); } - let started = Instant::now(); + let started = self.clock.now(); let state = device.park_state()?; if device.position()? != tokens.len() as u64 { return Err(Error::IdentityMismatch); @@ -171,7 +171,7 @@ impl PrefixServe { self.seen_state_bytes = Some(state.byte_size()); let new_blocks = blocks.len(); let bytes = state.byte_size() + tail.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); - let park_ms = started.elapsed().as_secs_f64() * 1e3; + let park_ms = self.clock.since(started).as_secs_f64() * 1e3; self.store.commit_tail_keeping(candidate, tokens, state, blocks, tail, keep_end).map_err(|_| Error::IdentityMismatch)?; self.park_ms_request += park_ms; self.admitted_request += 1; @@ -195,7 +195,7 @@ impl PrefixServe { /// The metrics line. /// Drop the sessions nobody used for the retention time (called from the idle loop); returns how many nodes went. pub(in super::super::super) fn expire_idle(&mut self) -> usize { - self.store.set_now(wall_ms()); + self.store.set_now(self.wall_ms()); self.store.expire() } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs index 7057ab06..adc7040a 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/tests.rs @@ -3,7 +3,7 @@ use super::*; use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; -const G: usize = 256; +pub(super) const G: usize = 256; /// A payload with a size. struct Bytes(usize); @@ -13,7 +13,7 @@ impl ByteSize for Bytes { } } /// The state a fake device parks: where the session stood, and a digest of the tokens it had read. -struct State { +pub(super) struct State { position: u64, digest: u64, } @@ -22,7 +22,7 @@ impl ByteSize for State { 100 } } -struct Block { +pub(super) struct Block { cells: Vec, } impl ByteSize for Block { @@ -33,7 +33,7 @@ impl ByteSize for Block { /// A device whose positional buffer is a token per cell and whose recurrent state is a digest of every token /// read in order, so a restore that mixes up cells or states is visible as soon as it is used. -struct Fake { +pub(super) struct Fake { cells: Vec, position: u64, digest: u64, @@ -42,7 +42,7 @@ struct Fake { available: Option, } impl Fake { - fn new() -> Self { + pub(super) fn new() -> Self { Self { cells: vec![-1; 1 << 16], position: 0, digest: 0, log: Vec::new(), fail_import: false, available: Some(1 << 40) } } fn read(&mut self, tokens: &[i32], first: usize) { @@ -95,7 +95,7 @@ impl PrefixDevice for Fake { } } -fn cfg() -> PrefixConfig { +pub(super) fn cfg() -> PrefixConfig { PrefixConfig { block_tokens: G, ..PrefixConfig::auto() } } fn serve() -> PrefixServe { @@ -104,7 +104,7 @@ fn serve() -> PrefixServe { /// One request against the fake: begin, read the plan's chunks on the grid, finish. Returns (start, digest the /// session holds at the end of the prefill = a function of all tokens read). -fn request(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], stop_after_chunks: Option) -> (Option, u64) { +pub(super) fn request(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], stop_after_chunks: Option) -> (Option, u64) { let start = s.begin(d, prompt).unwrap(); let resume = match &start { Some(st) => st.resume, diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 6e8b57c0..086f3231 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -72,6 +72,7 @@ use conversation::{ResumeDevice, ServeConversation}; #[path = "original_serve_prefix.rs"] mod prefix; pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; +use leleka_obs::time::{AnyClock, Clock}; use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; @@ -131,6 +132,8 @@ pub(crate) struct StackConfig { pub(crate) expert_tier: ExpertTierConfig, /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan of `capacity`). pub(crate) loan_tiers: bool, + /// The time of the request phases, the prefix cache's retention and the seed plan (the system clock by default). + pub(crate) clock: AnyClock, } /// One rung of the loan ladder: the arena layout for chunks of at most `rows` rows and the slots it needs. diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs index 038857e7..c9764f68 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_default_for_ttftmarks.rs @@ -9,11 +9,11 @@ impl Default for TtftMarks { } } impl TtftMarks { - pub(super) fn start() -> Self { - Self { started: Some(Instant::now()), ..Self::default() } + pub(super) fn start(clock: &impl Clock) -> Self { + Self { started: Some(clock.now()), ..Self::default() } } - pub(super) fn since(&self) -> f64 { - self.started.map_or(f64::NAN, |at| at.elapsed().as_secs_f64() * 1e3) + pub(super) fn since(&self, clock: &impl Clock) -> f64 { + self.started.map_or(f64::NAN, |at| clock.since(at).as_secs_f64() * 1e3) } pub(super) fn as_array(&self) -> [f64; 4] { [self.resumed, self.prefilled, self.assembled, self.first_round] @@ -38,6 +38,7 @@ impl StackConfig { kv_resident: leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS, conversation: Some(ConversationConfig::original()), prefix: None, + clock: AnyClock::System, expert_tier: ExpertTierConfig::off(), loan_tiers: serve.prefill_loan_tiers, } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs index ec126de0..6c8189f8 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs @@ -142,7 +142,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { None } else { let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); - let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); + let clock = config.clock.clone(); + let serve = PrefixServe::with_clock(prefix_config.clone(), config.capacity, bytes, &identity, clock); operator_note(&format!( "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", serve.block_tokens(), diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs index 5fa844bf..222a6e6e 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs @@ -20,7 +20,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { cancel: &mut dyn FnMut() -> bool, ) -> std::result::Result { self.apply_memory_directive(); - self.marks = TtftMarks::start(); + self.marks = TtftMarks::start(&self.config.clock); let max_context = self.config.max_context; let result = run_request(self, request, max_context, emit, cancel); self.note_memory(); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs index 599a132a..3693375c 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs @@ -125,7 +125,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { }, ); drop(p); - marks.assembled = marks.since(); + marks.assembled = marks.since(&config.clock); // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them // before a window or the tier's own bookkeeping touches the cache if std::mem::take(refill_pending) { @@ -240,7 +240,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } Ok(mut engine) => { crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); - let started = Instant::now(); + let started = config.clock.now(); let serve_span = profile::span("decode.serve"); let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { serve_request( @@ -252,12 +252,12 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { &request.eos, |tokens| { if marks.first_round.is_nan() { - marks.first_round = marks.since(); + marks.first_round = marks.since(&config.clock); } emit(tokens) }, &mut *cancel, - || started.elapsed().as_secs_f64() * 1e3, + || config.clock.since(started).as_secs_f64() * 1e3, ) }); drop(serve_span); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs index 2afb1134..20fd69a4 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs @@ -69,7 +69,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let tier = &self.config.expert_tier; let (max, keep, usage) = (tier.seed_swaps, tier.seed_keep, tier.seed_usage); let Some(cache) = self.expert_cache.as_mut() else { return Ok(()) }; - let started = Instant::now(); + let started = self.config.clock.now(); let max_rows = tier.seed_max_rows; if max_rows > 0 { let rows = original_serve_seed::summarize(counts, &[]).rows; @@ -81,11 +81,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } } let swaps = original_serve_seed::plan(counts, cache, max, keep); - let planned = started.elapsed(); + let planned = self.config.clock.since(started); let mut report = original_serve_seed::summarize(counts, &swaps); original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; report.plan_ms = planned.as_secs_f64() * 1e3; - report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3; + report.queue_ms = (self.config.clock.since(started) - planned).as_secs_f64() * 1e3; self.residency.add_usage(counts, usage); if crate::settings::process().diagnostics.seed_trace { eprintln!( diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs index 0c006fd8..24884461 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs @@ -121,15 +121,15 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { resume } fn prefill(&mut self, request: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<(), SpecError> { - let started = Instant::now(); + let started = self.config.clock.now(); self.timing = (0.0, 0.0); - self.marks.resumed = self.marks.since(); + self.marks.resumed = self.marks.since(&self.config.clock); let result = self.prefill_phase(request, resume, cancel); if matches!(result, Err(SpecError::Cancelled)) { self.keep_conversation_after_cancelled_prefill(request); } - self.marks.prefilled = self.marks.since(); - self.timing.0 = started.elapsed().as_secs_f64() * 1e3; + self.marks.prefilled = self.marks.since(&self.config.clock); + self.timing.0 = self.config.clock.since(started).as_secs_f64() * 1e3; result } fn decode( @@ -138,7 +138,7 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { emit: &mut dyn FnMut(&[i32]) -> Result<()>, cancel: &mut dyn FnMut() -> bool, ) -> std::result::Result { - let started = Instant::now(); + let started = self.config.clock.now(); let tier0 = self.residency.stats; let result = self.decode_phase(request, emit, cancel); match (result.is_ok(), self.tail_consumed.take()) { @@ -160,7 +160,7 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { } } } - self.timing.1 = started.elapsed().as_secs_f64() * 1e3; + self.timing.1 = self.config.clock.since(started).as_secs_f64() * 1e3; profile::add("decode.phase", self.timing.1); if profile::enabled() { let t1 = self.residency.stats; From e4340f077d119b628b7ec82a8424252f0b67d774 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 23:23:01 +0100 Subject: [PATCH 3/5] STRA-338 S14: the GPU ordinal reaches the telemetry sampler through Run, not a process static --- crates/leleka-runtime/src/backend/config.rs | 6 ------ crates/leleka-runtime/src/backend/load_cuda.rs | 2 +- crates/leleka-runtime/src/backend_original_serve.rs | 8 ++++---- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/crates/leleka-runtime/src/backend/config.rs b/crates/leleka-runtime/src/backend/config.rs index b0a99963..66715df7 100644 --- a/crates/leleka-runtime/src/backend/config.rs +++ b/crates/leleka-runtime/src/backend/config.rs @@ -154,9 +154,3 @@ impl EvaluationExecution { } } } - -/// Validated sampling plan of a request: `None` keeps the ordinary greedy path -/// (temperature 0 and no penalty), `Some` carries the Original `SamplerParams` for -/// the host sampler. `entropy` seeds requests that carry no seed (Original `seed = 0`). -/// The CUDA ordinal of the loaded device, for the telemetry sampler (NVML indexes the same physical order). -pub(crate) static GPU_ORDINAL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); diff --git a/crates/leleka-runtime/src/backend/load_cuda.rs b/crates/leleka-runtime/src/backend/load_cuda.rs index a61b78d8..a14b8ba7 100644 --- a/crates/leleka-runtime/src/backend/load_cuda.rs +++ b/crates/leleka-runtime/src/backend/load_cuda.rs @@ -11,7 +11,6 @@ pub(super) fn open_context<'d>( config: &NativeBackendConfig, driver: &'d Driver, ) -> Result>, BackendError> { - GPU_ORDINAL.store(config.gpu_device_ordinal, Ordering::Relaxed); let device = driver .device(config.gpu_device_ordinal as i32) .map_err(|_| load_failure(LoadPhase::Device, unavailable("CUDA device unavailable")))?; @@ -107,6 +106,7 @@ pub(super) fn launch_original<'d>( options, model_files: vec![env.config.shard0.clone(), env.config.shard1.clone()], clock: env.clock, + gpu_ordinal: env.config.gpu_device_ordinal, }) } #[cfg(not(all( diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index 380f607a..8deb3f40 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -300,7 +300,6 @@ mod runner { Tokenizer, Usage, Utf8Pending, GENERATION_TIMEOUT, QUEUE, }; use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY}; - use crate::idle_sweep::IdleSweep; type GpuProbe = Box Option + Send + Sync>; @@ -336,7 +335,7 @@ mod runner { original_serve_verifier::ServeFailure, }; use leleka_backend_api::GenerationRequest; - use leleka_obs::time::{Clock, SystemClock}; + use {crate::idle_sweep::IdleSweep, leleka_obs::time::{Clock, SystemClock}}; use std::{ path::PathBuf, rc::Rc, @@ -363,6 +362,7 @@ mod runner { /// The model files, for the start-up report only (size and mtime are read; the content never is). pub(in super::super) model_files: Vec, pub(in super::super) clock: SystemClock, + pub(in super::super) gpu_ordinal: u32, // for the telemetry sampler (NVML indexes the same physical order) } /// Host memory a reconfigure needs beside the soft floor: the reopened stack's pinned K/V (3.1 GiB at 262,144 cells), rings and pools. @@ -727,7 +727,7 @@ mod runner { /// Open the stack, answer the load, then serve commands until unload/shutdown. Returns the unload reply /// target, as `serve_load` does after its loop. pub(in super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError> { - let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files, clock } = args; + let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files, clock, gpu_ordinal } = args; // the settings can change at run time (`Command::Reconfigure`): this thread owns the current copy let mut options = options.clone(); let mut context_tokens = context_tokens; @@ -773,7 +773,7 @@ mod runner { leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None)); // operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); - let _telemetry = leleka_memory::telemetry::start(gpu_probe(crate::backend::GPU_ORDINAL.load(Ordering::Relaxed)), Duration::from_secs(1)); + let _telemetry = leleka_memory::telemetry::start(gpu_probe(gpu_ordinal), Duration::from_secs(1)); let mut stack = Some(stack); if shared.shutdown.load(Ordering::Acquire) { if let Some(stack) = stack.take() { From 2cc7b11fb3f280e306468c332e9002fd5b34c809 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 23:24:12 +0100 Subject: [PATCH 4/5] STRA-338 S14: admission tests on the scripted host --- .../src/governor/pressure_tests.rs | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/crates/leleka-memory/src/governor/pressure_tests.rs b/crates/leleka-memory/src/governor/pressure_tests.rs index d8d25527..281b47b6 100644 --- a/crates/leleka-memory/src/governor/pressure_tests.rs +++ b/crates/leleka-memory/src/governor/pressure_tests.rs @@ -124,3 +124,55 @@ fn a_stuck_reject_is_lifted_by_the_requests_themselves_once_the_sampler_is_five_ assert_eq!(g.admit(&SHAPE), Admission::Admit); assert_eq!(g.level(), Level::Shed); } + +#[test] +fn admission_follows_the_level_the_scripted_host_drives_it_to() { + // normal, then shed (requests are still served), then reject (503 with a Retry-After); an admit that gets past the + // level reads the host once more for its own transient, a refusal by level does not + let (g, _clock) = scripted(&[20_000, 20_000, 3000, 3000, 1024]); + g.sample_at(1000); + assert_eq!(g.admit(&SHAPE), Admission::Admit); + g.sample_at(2000); + assert_eq!(g.level(), Level::Shed); + assert_eq!(g.admit(&SHAPE), Admission::Admit, "shedding still serves"); + g.sample_at(3000); + let Admission::Refuse(refusal) = g.admit(&SHAPE) else { + panic!("rejecting must refuse") + }; + assert_eq!((refusal.status, refusal.code), (503, "memory_pressure")); + assert!(refusal.retry_after_secs >= 5, "{refusal:?}"); + let report = g.report(); + assert_eq!(report["counters"]["admitted"], 2); + assert_eq!(report["counters"]["rejected_memory_pressure"], 1); +} + +#[test] +fn a_request_whose_own_transient_would_cross_the_hard_floor_is_refused_on_the_scripted_host() { + // 2.1 GiB available: above the 2 GiB hard floor, but the 256 MiB transient of one request would cross it + let (g, _clock) = scripted(&[2150]); + let Admission::Refuse(refusal) = g.admit(&SHAPE) else { + panic!("must refuse") + }; + assert_eq!(refusal.code, "memory_pressure"); + assert!( + refusal.message.contains("hard floor"), + "{}", + refusal.message + ); +} + +#[test] +fn a_context_that_can_never_fit_is_a_400_and_does_not_read_the_host() { + let (g, _clock) = scripted(&[20_000]); + let Admission::Refuse(refusal) = g.admit(&RequestShape { + prompt_tokens: 262_144, + ..SHAPE + }) else { + panic!() + }; + assert_eq!( + (refusal.status, refusal.code), + (400, "context_length_exceeded") + ); + assert_eq!(g.report()["counters"]["rejected_context"], 1); +} From b19b83dff34fd919ea4de1d7b9205502bd47ed2d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 23:32:14 +0100 Subject: [PATCH 5/5] STRA-338 S14: Stopwatch for the prefix cache retention scale, PrefixServe::new keeps its size, S14 notes in tech-debt.md --- .../src/qwen_forward/original_serve_prefix.rs | 8 +-- .../original_serve_prefix/clock_tests.rs | 4 +- .../impl_prefixserve/impl_prefixserve_2.rs | 23 +++---- .../impl_originalservestack_2.rs | 2 +- crates/obs/src/time.rs | 2 +- crates/obs/src/time/clock.rs | 53 +++++++++++++++ docs/architecture/tech-debt.md | 65 ++++++++++++++++++- 7 files changed, 130 insertions(+), 27 deletions(-) diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs index 536900b2..91490daa 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs @@ -21,8 +21,7 @@ use super::super::contract::Error; use crate::prefix_cache::{ budget, fingerprint, ByteSize, Consider, PolicyParams, PrefixMatch, PrefixStore, PrefixSummary, Reject, Stats, StoreConfig, }; -use leleka_obs::time::{AnyClock, Clock}; -use std::time::Instant; +use leleka_obs::time::{AnyClock, Clock, Stopwatch}; /// What the operator asked for (`--prefix-cache-mib`, `--prefix-cache-block`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -152,9 +151,8 @@ pub(super) struct PrefixServe { shed: bool, /// Why the last checkpoint attempt was not taken, with the numbers (read once by the stack for its log line). note: Option, - /// The retention clock of the store (milliseconds since `epoch`) and the timers of the request phases. - clock: AnyClock, - epoch: Instant, + /// The retention clock of the store (milliseconds since the cache was built) and the timers of the request phases. + clock: Stopwatch, } #[cfg(test)] diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs index 200ed2bc..8bc78baa 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/clock_tests.rs @@ -9,7 +9,7 @@ use leleka_obs::time::ManualClock; fn idle_checkpoints_expire_when_the_clock_passes_the_retention_and_not_before() { let clock = ManualClock::new(); let mut s = - PrefixServe::with_clock(cfg(), 1024, 1 << 30, "test", AnyClock::from(clock.clone())); + PrefixServe::new(cfg(), 1024, 1 << 30, "test").with_clock(AnyClock::from(clock.clone())); let retention = cfg().policy.retention_ms; assert!( retention > 0, @@ -40,7 +40,7 @@ fn idle_checkpoints_expire_when_the_clock_passes_the_retention_and_not_before() fn a_request_renews_the_retention_of_the_checkpoints_it_used() { let clock = ManualClock::new(); let mut s = - PrefixServe::with_clock(cfg(), 1024, 1 << 30, "test", AnyClock::from(clock.clone())); + PrefixServe::new(cfg(), 1024, 1 << 30, "test").with_clock(AnyClock::from(clock.clone())); let retention = cfg().policy.retention_ms; let mut d = Fake::new(); let prompt: Vec = (0..(3 * G + 10) as i32).collect(); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs index 6f278cee..c5e29d25 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs @@ -8,19 +8,7 @@ use super::*; impl PrefixServe { /// `identity`: whatever makes two runtimes' caches interchangeable (model digest, KV format...), hashed with the /// block size into the summary's namespace. - #[cfg(test)] pub(in super::super::super) fn new(cfg: PrefixConfig, capacity: usize, budget_bytes: u64, identity: &str) -> Self { - Self::with_clock(cfg, capacity, budget_bytes, identity, AnyClock::System) - } - - /// [`Self::new`] with the clock of the retention scale and the phase timers. - pub(in super::super::super) fn with_clock( - cfg: PrefixConfig, - capacity: usize, - budget_bytes: u64, - identity: &str, - clock: AnyClock, - ) -> Self { let block_tokens = cfg.resolved_block(capacity); let namespace = fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION)); let store = PrefixStore::new(StoreConfig { @@ -47,14 +35,19 @@ impl PrefixServe { configured_budget: usize::try_from(budget_bytes).unwrap_or(usize::MAX), shed: false, note: None, - epoch: clock.now(), - clock, + clock: Stopwatch::start(AnyClock::System), } } + /// The same cache on another clock: the retention scale and the phase timers follow it from now on. + pub(in super::super::super) fn with_clock(mut self, clock: AnyClock) -> Self { + self.clock = Stopwatch::start(clock); + self + } + /// Milliseconds since this cache was built, on its clock (the store's wall-time scale for session retention). pub(in super::super::super) fn wall_ms(&self) -> u64 { - self.clock.since(self.epoch).as_millis() as u64 + self.clock.elapsed_ms() } /// Apply the memory governor's shed directive (`Governor::directive`): `Some(bytes)` evicts down to that budget (lowest diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs index 6c8189f8..f9a75c7f 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs @@ -143,7 +143,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } else { let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); let clock = config.clock.clone(); - let serve = PrefixServe::with_clock(prefix_config.clone(), config.capacity, bytes, &identity, clock); + let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity).with_clock(clock); operator_note(&format!( "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", serve.block_tokens(), diff --git a/crates/obs/src/time.rs b/crates/obs/src/time.rs index 44b31c1f..5a16349b 100644 --- a/crates/obs/src/time.rs +++ b/crates/obs/src/time.rs @@ -2,7 +2,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; mod clock; -pub use clock::{AnyClock, Clock, ManualClock, SystemClock}; +pub use clock::{AnyClock, Clock, ManualClock, Stopwatch, SystemClock}; /// Milliseconds since the Unix epoch. pub fn now_ms() -> u64 { diff --git a/crates/obs/src/time/clock.rs b/crates/obs/src/time/clock.rs index 5a391ce7..a2dd4364 100644 --- a/crates/obs/src/time/clock.rs +++ b/crates/obs/src/time/clock.rs @@ -115,6 +115,39 @@ impl From for AnyClock { } } +/// A clock and the reading it had when it was started: a scale of time since then, and still a [`Clock`] itself. +#[derive(Clone, Debug)] +pub struct Stopwatch { + clock: C, + epoch: Instant, +} + +impl Stopwatch { + /// Start counting now. + pub fn start(clock: C) -> Self { + Self { + epoch: clock.now(), + clock, + } + } + + /// Time since [`Self::start`]. + pub fn elapsed(&self) -> Duration { + self.clock.since(self.epoch) + } + + /// Whole milliseconds since [`Self::start`]. + pub fn elapsed_ms(&self) -> u64 { + u64::try_from(self.elapsed().as_millis()).unwrap_or(u64::MAX) + } +} + +impl Clock for Stopwatch { + fn now(&self) -> Instant { + self.clock.now() + } +} + #[cfg(test)] mod tests { use super::*; @@ -172,6 +205,26 @@ mod tests { assert!(AnyClock::default().since(Instant::now()) < Duration::from_secs(1)); } + #[test] + fn a_stopwatch_counts_from_its_start_on_the_clock_it_was_given() { + let clock = ManualClock::new(); + clock.advance_ms(900); + let watch = Stopwatch::start(AnyClock::from(clock.clone())); + assert_eq!(watch.elapsed_ms(), 0); + clock.advance_ms(1999); + assert_eq!( + (watch.elapsed_ms(), watch.elapsed()), + (1999, Duration::from_millis(1999)) + ); + let mark = watch.now(); + clock.advance_ms(1); + assert_eq!( + watch.since(mark), + Duration::from_millis(1), + "it is a clock too" + ); + } + #[test] fn a_reference_to_a_clock_is_a_clock() { fn elapsed(clock: impl Clock, start: Instant) -> Duration { diff --git a/docs/architecture/tech-debt.md b/docs/architecture/tech-debt.md index 730481d0..1f3fd072 100644 --- a/docs/architecture/tech-debt.md +++ b/docs/architecture/tech-debt.md @@ -26,9 +26,9 @@ limits except the one line named first. What was moved verbatim in S5a and is st | `config.rs` | the `*_EXECUTION` identity strings are single lines of 120 to 200 columns | string continuation, with the golden digest test as the guard | Process-wide state and reads that the policy file `architecture.json` counts and that this directory still holds: -`RECONFIGURING`, `INSTANCE` and `GPU_ORDINAL` (process globals, S14), `Instant::now()` in `generate*.rs`, `utf8.rs` and -`sources.rs` (Clock, S14), and the `Box` returned by the factories (startup composition only). The -environment reads that were here (`LELEKA_ORIGINAL_SERVE_GGUF_PLE`, `LELEKA_PUBLIC_EVALUATION`) now read `Settings` +`RECONFIGURING` and `INSTANCE` (process atomics that `config.rs` still owns, see S14 below), and the +`Box` returned by the factories (startup composition only). The `Instant::now()` sites of `generate*.rs`, +`utf8.rs`, `sources.rs` and `GPU_ORDINAL` moved in S14. The environment reads that were here (`LELEKA_ORIGINAL_SERVE_GGUF_PLE`, `LELEKA_PUBLIC_EVALUATION`) now read `Settings` (S13, below). `qwen_forward/moe_weight_cache.rs` gained three `pub(crate) use` lines (`AdaptiveWitness`, `LearnedMainWitness`, @@ -90,3 +90,62 @@ Functions this step touched that were already over the limits (a few lines chang `spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots`, and three lines of 144 to 173 columns that were already there (`impl_default_for_ttftmarks.rs` header, `impl_originalservestack_2.rs` arm lines, `backend_original_serve.rs` capture call). + +## Clock and MemoryPressure (STRA-338 S14) + +**Clock** (`leleka_obs::time`, `time/clock.rs`): `trait Clock { fn now(&self) -> Instant; fn since(&self, earlier: Instant) -> Duration }` +with `SystemClock` (zero-sized, the only production `Instant::now()` of the port), `ManualClock` (shared timeline, +`advance`, and `ticking(step)` which moves after every reading so a polling loop with a deadline ends in a known number +of rounds), `AnyClock` (an enum of the two, for the owner that cannot be generic) and `Stopwatch` (a clock plus its +start: "milliseconds since"). The reading stays a plain `Instant`, so values from either clock are stored and compared +as before. Rule: a clock is read at coarse points (a request, a tile, a decision, a sampling tick); hot loops compare +against the reading taken at their start (`run.clock.since(start)` is a statically dispatched call on a generic `C` +that is `SystemClock` in production). + +Where it is injected: + +| Place | How | +| --- | --- | +| `Generation` (`generate.rs`, `generate_mtp.rs`) | the request start and the per-step deadline checks; `LoadEnv::clock` hands `SystemClock` to `build_run` | +| `emit_terminal`, `emit_event` (`utf8.rs`; the second one replaces two identical copies in `generate.rs` and the Original serve loop) | the 30 s backpressure limit | +| `verify_sources_parallel` | one reading per phase, passed to `load_clock::span` | +| `measurement::Recorder` | prefill and decode durations of an observed request | +| Original serve loop (`backend_original_serve.rs`, `Run::clock`) | request deadline, telemetry instants, reconfigure duration, `idle_sweep::IdleSweep` (the 15 s housekeeping cadence, its own tested type) | +| `StackConfig::clock: AnyClock` | TTFT marks, the seed plan timers, the prefix device phase timers, and the clock of `PrefixServe` | +| `PrefixServe::with_clock` (a `Stopwatch`) | the retention scale (`wall_ms`, now milliseconds since the cache was built instead of a process `OnceLock`: only differences are used) and the lookup, import and park timers | +| leleka-memory: `Governor::with_parts`, `Ledger::with_clock`, `telemetry::start_with_clock`, `request_started_at`/`tokens_delivered_at`, `smi::probe_with_clock` | uptime and shed cadence, stage timing, the sampler tick, the in-flight request clocks (the old entry points call the same code with `SystemClock`) | + +Still on `std::time::Instant` on purpose: the per-window and per-miss timers of the CPU expert pool, lookahead, +residency lag and the verify engine, the prefill/GDN profile spans, `owner_wall_profile` (diagnostics inside the +decode loop, one reading per kernel or per miss: a clock parameter there is the engine-core step, S19); `load_clock.rs` +(a process-wide lap printer behind a `Mutex`); `DBG_T0` (debug trace epoch); `open_tier_fn` (one startup log line); +`smi::query` (a subprocess wait loop, real I/O). The gateway and control-plane crates keep their own sites for the +gateway track. + +**MemoryPressure** (`leleka_memory::pressure_port`): `trait MemoryPressure: ProcSource + Send + Sync { fn facts(&self) -> HostFacts }`. +`ProcPressure` is the production adapter (`/proc` and `/sys` on Linux, the Win32 text renderings of +`winproc.rs` on Windows, parsed by `HostFacts::probe` exactly as before); `ScriptedPressure` hands out one scripted +reading per probe, the last one repeating (`available_mib(&[..])`). The governor reads the host only through it +(`probe`, `available_now`, the sample, the lock allowance and the heal check); it is also a `ProcSource` because the +residency guard and the census still read single files (`smaps`). `Governor::new(cfg, Arc)` keeps its +signature; `with_pressure` and `with_parts(cfg, pressure, AnyClock)` are the composition points. Tests drive rising, +falling and flapping pressure, the once-a-second shed step, the stale-sampler fallback and the admission decisions +without a sleep (`governor/pressure_tests.rs`). + +Process globals: `GPU_ORDINAL` is gone (the ordinal travels in `Run`, the value it always had), and the retention +`OnceLock` with it. Left, and why: `RECONFIGURING` (one flag for every backend of the process; moving it into +`Shared` would make concurrent backends independent, which is a behaviour change for a process that hosts two), +`INSTANCE` (the owner id counter that `spawn_backend_configured` draws from; it needs a spawner object that the callers +do not have), `Governor::global()` (about twenty calls in the runtime; they need a memory handle on the stack, the +conversation manager and the prefix cache, the same S19 move as `settings::process()`), `serving_cells()` (30 reads of +one validated constant), the two `std::cell::OnceCell` fields (per-instance lazy cells that the pattern also matches), +`NO_TRIM_FILE`, `heap::OFF` and `TUNING` (environment caches that belong to the Settings follow-up). + +Ratchets (totals over the workspace): `instant-now` 242 -> 209 (leleka-runtime 42 -> 17, leleka-memory 12 -> 1, +leleka-obs 0 -> 3 for the three adapters), `process-global` 267 -> 265, `dyn-trait` 215 -> 215. Functions this step +touched that were already over the limits and are not made worse: `Governor::with_parts` (35 lines, the old `new` had +34), `seed_residency` (34, as before), `guard_archive_extents`, +`residency_tick`, `telemetry::render`, the Original serve `generate` and `run`, `decode_phase`, `OriginalServeStack::open`. +Follow-ups: thread one clock and one memory handle through the engine core when it is extracted (S19), after which +`StackConfig::clock` and `LoadEnv::clock` become the generic parameter of the stack; a settings crate for the +environment caches above; `RECONFIGURING` and `INSTANCE` with a spawner object.