From b19b83dff34fd919ea4de1d7b9205502bd47ed2d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 23:32:14 +0100 Subject: [PATCH] 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.