diff --git a/architecture-baseline.json b/architecture-baseline.json index 9a604449..863b1602 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -3,11 +3,7 @@ "violations": [], "oversize": {}, "source": { - "dyn-trait:leleka-engine-qwen35-cuda": 9, - "env-read:leleka-control-plane": 3, - "instant-now:leleka-control-plane": 15, - "instant-now:leleka-engine-host": 4, - "process-global:leleka-control-plane": 2 + "dyn-trait:leleka-engine-qwen35-cuda": 9 }, "mechanical_names": [] } diff --git a/control-plane/src/backend_worker/attach.rs b/control-plane/src/backend_worker/attach.rs index 387bca7b..edfe4819 100644 --- a/control-plane/src/backend_worker/attach.rs +++ b/control-plane/src/backend_worker/attach.rs @@ -1,8 +1,9 @@ //! The attach loop of the backend worker: wait for the engine to load the model, serve requests and control //! messages while it is there, and attach again when it is lost. +use crate::{adapters::SystemClock, ports::Clock}; use super::{ - Arc, BackendWorkerConfig, Context, Control, Engine, GenerationCommand, Instant, LoadReply, RwLock, Served, + Arc, BackendWorkerConfig, Context, Control, Engine, GenerationCommand, LoadReply, RwLock, Served, WorkerInbox, WorkerState, WorkerStatus, api, mpsc, on_engine, refresh_prefix_view, send_failure, serve_one, update, watch, }; @@ -199,7 +200,7 @@ impl AttachLoop { .await; self.status.write().await.output_cap = Some(self.config.max_output_tokens); self.status.write().await.text_level_engine = true; - self.status.write().await.last_activity = Some(Instant::now()); + self.status.write().await.last_activity = Some(SystemClock.now()); } fn answer_waiting_loads(&mut self) { diff --git a/control-plane/src/backend_worker/generation_run.rs b/control-plane/src/backend_worker/generation_run.rs index c0c334d3..15d07415 100644 --- a/control-plane/src/backend_worker/generation_run.rs +++ b/control-plane/src/backend_worker/generation_run.rs @@ -1,6 +1,7 @@ //! The loop of one generation: what wakes the worker (the engine's events, the deadlines, the client going away, //! the shutdown) and what each wake-up does, ending with the terminal event for the HTTP layer. +use crate::{adapters::SystemClock, ports::Clock}; use super::{ BackendWorkerConfig, Cancel, Conclusion, Duration, Engine, Event, GenerationCommand, Instant, RwLock, STOP_LITERALS, Served, WorkerStatus, api, conclude, deliver, fail_command, mpsc, text_tokens, trigger_cancel, @@ -141,7 +142,7 @@ impl<'a> Run<'a> { cancel: None, first_delta: None, delivered: 0, - last_progress: Instant::now(), + last_progress: SystemClock.now(), deadline: ctx .config .generation_timeout @@ -213,7 +214,7 @@ impl<'a> Run<'a> { async fn begin_cancel(&mut self, cause: Cancel) { self.cancel = Some(cause); - self.drain_deadline = Some(Instant::now() + self.ctx.config.cancel_drain_timeout); + self.drain_deadline = Some(SystemClock.now() + self.ctx.config.cancel_drain_timeout); trigger_cancel(self.ctx.engine, &self.id).await; } @@ -230,7 +231,7 @@ impl<'a> Run<'a> { } async fn on_item(&mut self, item: Item) -> Option { - self.last_progress = Instant::now(); + self.last_progress = SystemClock.now(); match item { Some(Ok(event)) => self.on_event(event).await, Some(Err(api::StreamError::MissingTerminal)) | None => { diff --git a/control-plane/src/memory_view.rs b/control-plane/src/memory_view.rs index ab2796cf..ac4d3c98 100644 --- a/control-plane/src/memory_view.rs +++ b/control-plane/src/memory_view.rs @@ -8,6 +8,7 @@ use std::sync::RwLock; use std::sync::atomic::{AtomicU64, Ordering}; +use leleka_obs::time::{AnyClock, Clock}; use std::time::{Duration, Instant}; use axum::{ @@ -50,6 +51,7 @@ pub struct MemoryView { /// A minute of the headline telemetry series (`GET /metrics` `history`). series: crate::hardware_view::Series, gated: AtomicU64, + clock: AnyClock, } impl MemoryView { @@ -59,7 +61,7 @@ impl MemoryView { .and_then(|text| serde_json::from_str::(&text).ok()) .filter(Value::is_object); if let Ok(mut latest) = self.latest.write() { - *latest = value.map(|value| (value, Instant::now())); + *latest = value.map(|value| (value, self.clock.now())); } } @@ -72,7 +74,7 @@ impl MemoryView { self.series.push(&crate::hardware_view::hardware_now(value)); } if let Ok(mut latest) = self.telemetry.write() { - *latest = value.map(|value| (value, Instant::now())); + *latest = value.map(|value| (value, self.clock.now())); } } @@ -95,13 +97,13 @@ impl MemoryView { pub fn brief(&self) -> Option { let telemetry = self.telemetry.read().ok()?; let (document, at) = telemetry.as_ref()?; - if at.elapsed() > FRESH_FOR { + if self.clock.since(*at) > FRESH_FOR { return None; } let gate = self.latest.read().ok().and_then(|latest| { latest .as_ref() - .filter(|(_, at)| at.elapsed() <= FRESH_FOR) + .filter(|(_, at)| self.clock.since(*at) <= FRESH_FOR) .and_then(|(report, _)| report["gate"]["level"].as_str().map(str::to_owned)) }); Some(Brief { @@ -120,9 +122,9 @@ impl MemoryView { return Value::Null; }; match latest.as_ref() { - Some((value, at)) if at.elapsed() <= FRESH_FOR => { + Some((value, at)) if self.clock.since(*at) <= FRESH_FOR => { let mut value = value.clone(); - value["age_ms"] = json!(at.elapsed().as_millis() as u64); + value["age_ms"] = json!(self.clock.since(*at).as_millis() as u64); value } _ => Value::Null, @@ -137,7 +139,7 @@ impl MemoryView { match latest.as_ref() { Some((value, at)) => { let mut value = value.clone(); - value["age_ms"] = json!(at.elapsed().as_millis() as u64); + value["age_ms"] = json!(self.clock.since(*at).as_millis() as u64); value["gate_rejections"] = json!(self.gated.load(Ordering::Relaxed)); value } @@ -149,7 +151,7 @@ impl MemoryView { pub fn closed(&self) -> Option { let latest = self.latest.read().ok()?; let (report, at) = latest.as_ref()?; - if at.elapsed() > FRESH_FOR || report["gate"]["level"] != "reject" { + if self.clock.since(*at) > FRESH_FOR || report["gate"]["level"] != "reject" { return None; } self.gated.fetch_add(1, Ordering::Relaxed); diff --git a/control-plane/src/metrics.rs b/control-plane/src/metrics.rs index 9084b198..b363abf3 100644 --- a/control-plane/src/metrics.rs +++ b/control-plane/src/metrics.rs @@ -5,6 +5,7 @@ use std::{ time::{Instant, SystemTime, UNIX_EPOCH}, }; +use leleka_obs::time::{Clock as _, SystemClock}; use serde::Serialize; use serde_json::{Value, json}; @@ -255,7 +256,7 @@ impl GenerationMetrics { pub fn start(&mut self) { self.started = self.started.saturating_add(1); - self.active_since = Some(Instant::now()); + self.active_since = Some(SystemClock.now()); self.started_wall = Some(SystemTime::now()); } diff --git a/control-plane/src/prefix_view.rs b/control-plane/src/prefix_view.rs index 43098000..cbd84296 100644 --- a/control-plane/src/prefix_view.rs +++ b/control-plane/src/prefix_view.rs @@ -6,6 +6,7 @@ //! shows it as `prefix_cache`, and `POST /v1/prefix_match` answers "how much of this prompt do you hold" from it. The //! answer is a hint about a snapshot, never a promise: the engine may have evicted a head since. +use leleka_obs::time::{AnyClock, Clock}; use std::{collections::HashMap, sync::RwLock, time::Instant}; use serde_json::{Value, json}; @@ -16,6 +17,7 @@ pub const MAX_HASHES: usize = 16_384; #[derive(Default)] pub struct PrefixView { latest: RwLock>, + clock: AnyClock, } /// Why a query was refused. @@ -68,7 +70,7 @@ impl PrefixView { .and_then(|text| serde_json::from_str::(&text).ok()) .filter(Value::is_object); if let Ok(mut latest) = self.latest.write() { - *latest = value.map(|value| (value, Instant::now())); + *latest = value.map(|value| (value, self.clock.now())); } } @@ -80,7 +82,7 @@ impl PrefixView { match latest.as_ref() { Some((value, at)) => { let mut value = value.clone(); - value["age_ms"] = json!(at.elapsed().as_millis() as u64); + value["age_ms"] = json!(self.clock.since(*at).as_millis() as u64); value } None => Value::Null, @@ -117,7 +119,7 @@ impl PrefixView { "block_tokens": summary["block_tokens"], "cached_tokens": cached, "truncated": summary["truncated"], - "age_ms": at.elapsed().as_millis() as u64, + "age_ms": self.clock.since(*at).as_millis() as u64, })) } } diff --git a/control-plane/src/request_log/request_context.rs b/control-plane/src/request_log/request_context.rs index c1545b36..ec297991 100644 --- a/control-plane/src/request_log/request_context.rs +++ b/control-plane/src/request_log/request_context.rs @@ -78,13 +78,6 @@ pub fn class_of_status(status: u16) -> &'static str { } } -/// The serving profile named by `LELEKA_PROFILE`, when it is set and not empty. -fn profile_from_env() -> Option { - std::env::var("LELEKA_PROFILE") - .ok() - .filter(|p| !p.is_empty()) -} - /// Who a request is: its id, the endpoint it asked for, its session tag and the model it was sent to. pub struct ReqIdentity { pub id: String, @@ -106,7 +99,7 @@ impl ReqCtx { endpoint: identity.endpoint, stream: None, model: identity.model, - profile: profile_from_env(), + profile: crate::env_settings::serving_profile(), admitted: clock.now(), engine_start: None, first_token: None, diff --git a/control-plane/src/request_monitor/capture.rs b/control-plane/src/request_monitor/capture.rs index 3e7d7e14..02b47186 100644 --- a/control-plane/src/request_monitor/capture.rs +++ b/control-plane/src/request_monitor/capture.rs @@ -1,7 +1,8 @@ //! The request monitor: ring of records, the response tap that fills a record, and capture of a request. +use leleka_obs::time::{Clock as _, SystemClock}; use super::{ - Arc, BODY_LIMIT, Body, Bytes, Context, HeaderValue, Instant, IntoResponse, LINE_LIMIT, Mutex, Next, Pin, Poll, + Arc, BODY_LIMIT, Body, Bytes, Context, HeaderValue, IntoResponse, LINE_LIMIT, Mutex, Next, Pin, Poll, RESPONSE_LIMIT, RETENTION, Record, Request, RequestMonitor, Response, Shared, State, StatusCode, Stream, Tap, Value, VecDeque, clipped, header, json, now_unix, }; @@ -50,7 +51,7 @@ fn queued_record(path: &str, request: &Value, (input, input_truncated): (String, response_truncated: false, wallclock_s: None, finished_at: None, - clock: Instant::now(), + clock: SystemClock.now(), } } diff --git a/control-plane/src/responses/errors.rs b/control-plane/src/responses/errors.rs index 3636eeb5..de6c3fd2 100644 --- a/control-plane/src/responses/errors.rs +++ b/control-plane/src/responses/errors.rs @@ -72,6 +72,5 @@ pub(super) fn log_generation_failure(message: &str) { } pub(super) fn debug_failed_output() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("STRATA_DEBUG_FAILED_OUTPUT").is_some_and(|v| v == "1")) + crate::env_settings::debug_failed_output() } diff --git a/control-plane/src/stage_trace.rs b/control-plane/src/stage_trace.rs index 84e0d8c2..6cfc4b2f 100644 --- a/control-plane/src/stage_trace.rs +++ b/control-plane/src/stage_trace.rs @@ -6,6 +6,8 @@ //! a per-stage accumulator that [`drain`] hands out (the replay harness `examples/cp_replay.rs` reads it after each //! request), and with `STRATA_STAGE_TRACE=log` each span also writes one `stage t_unix_ms=` line to //! stderr. Spans never carry request content, only names and durations. +use crate::env_settings::StageTrace; +use leleka_obs::time::{Clock, SystemClock}; use std::{ collections::BTreeMap, sync::{ @@ -25,10 +27,10 @@ static MODE: AtomicU8 = AtomicU8::new(UNSET); fn mode() -> u8 { match MODE.load(Ordering::Relaxed) { UNSET => { - let value = match std::env::var("STRATA_STAGE_TRACE").as_deref() { - Ok("1") => ON, - Ok("log") => LOG, - _ => OFF, + let value = match crate::env_settings::stage_trace() { + StageTrace::Spans => ON, + StageTrace::SpansAndLog => LOG, + StageTrace::Off => OFF, }; MODE.store(value, Ordering::Relaxed); value @@ -99,7 +101,7 @@ impl Drop for Span { pub fn span(name: &'static str) -> Span { Span { - started: (mode() >= ON).then(|| (name, Instant::now())), + started: (mode() >= ON).then(|| (name, SystemClock.now())), } } diff --git a/control-plane/src/worker/generation.rs b/control-plane/src/worker/generation.rs index ecbcbf47..ae13afc6 100644 --- a/control-plane/src/worker/generation.rs +++ b/control-plane/src/worker/generation.rs @@ -5,6 +5,7 @@ use std::{ops::ControlFlow, pin::Pin}; use leleka_serving_policy::{reasoning::BudgetTracker, watchdog}; use tokio::time::Sleep; +use crate::{adapters::SystemClock, ports::Clock}; use super::{ AsyncWriteExt, BufReader, ChildStdin, Done, Duration, Event, Generate, GenerationCommand, RwLock, STALL_PREFIX, STOP_DRAIN_TIMEOUT, WorkerStatus, combine_done, deliver, finish, send_failure, wire, @@ -35,7 +36,7 @@ async fn request_stop(pipe: &mut ChildStdin, deadline: Pin<&mut Sleep>) -> Resul /// Restart the 20 second clock a STOP has to be answered within. pub(super) fn arm_stop_deadline(deadline: Pin<&mut Sleep>) { - deadline.reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); + deadline.reset(SystemClock.now() + STOP_DRAIN_TIMEOUT); } /// The stall watchdog seen from outside: one poll a second over the engine's lines. diff --git a/control-plane/src/worker/run_session.rs b/control-plane/src/worker/run_session.rs index af27c2b1..a3b9021c 100644 --- a/control-plane/src/worker/run_session.rs +++ b/control-plane/src/worker/run_session.rs @@ -1,5 +1,6 @@ //! One engine process from spawn to exit: start, wait for READY, then serve requests and control messages. +use crate::{adapters::SystemClock, ports::Clock}; use super::engine_io::{EngineLines, EnginePipes, generate_within_deadline, spawn_engine}; use super::{ AsyncBufReadExt, BufReader, Child, ChildStdin, Control, Duration, GenerationCommand, LoadReply, RwLock, @@ -193,7 +194,7 @@ impl Session<'_> { return Err(self.startup_failed().await); }; update(self.status, WorkerState::Ready, Some(max_context)).await; - self.status.write().await.last_activity = Some(tokio::time::Instant::now()); + self.status.write().await.last_activity = Some(SystemClock.now()); for reply in self.waiting.drain(..) { let _ = reply.send(Ok(())); } @@ -360,7 +361,7 @@ impl Session<'_> { } return Some(SessionExit::RuntimeFailed); } - self.status.write().await.last_activity = Some(tokio::time::Instant::now()); + self.status.write().await.last_activity = Some(SystemClock.now()); None } } diff --git a/control-plane/src/worker/worker_entry.rs b/control-plane/src/worker/worker_entry.rs index 1f8ae4c4..0b7781a1 100644 --- a/control-plane/src/worker/worker_entry.rs +++ b/control-plane/src/worker/worker_entry.rs @@ -2,6 +2,7 @@ //! refused reconfigure) and the gate before a reload; also the methods of `GenerationResult` and the defaults of //! `WorkerStatus` and `WorkerConfig`. +use crate::{adapters::SystemClock, ports::Clock}; use super::{ Arc, BeforeLoad, Command, Control, Duration, Event, GenerationCommand, GenerationResult, LoadError, LoadReply, OsString, RwLock, Stdio, Wake, WorkerConfig, WorkerState, WorkerStatus, mpsc, oneshot, run_supervised, timeout, @@ -182,10 +183,10 @@ async fn run_before_load(before: &BeforeLoad) { /// The free-VRAM gate: memory another process just gave back can take a moment. async fn check_free_vram(config: &WorkerConfig) -> Result<(), LoadError> { - let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + let deadline = SystemClock.now() + Duration::from_secs(15); let mut free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; while free.is_some_and(|f| f < config.min_free_vram_mib) - && tokio::time::Instant::now() < deadline + && SystemClock.now() < deadline { tokio::time::sleep(Duration::from_millis(500)).await; free = crate::cuda_memory::free_mib(config.cuda_memory.as_ref()).await; diff --git a/desktop-core/src/gateway/responses.rs b/desktop-core/src/gateway/responses.rs index afad55a6..22debb2d 100644 --- a/desktop-core/src/gateway/responses.rs +++ b/desktop-core/src/gateway/responses.rs @@ -4,6 +4,7 @@ // The error value is the finished HTTP response: it is returned as it is, so it is large by design. #![allow(clippy::result_large_err)] +use crate::clock::{Clock, RuntimeClock}; use super::{ AdmissionError, Body, Bytes, Config, Duration, Gateway, HashSet, HeaderMap, InFlight, IntoResponse, Response, State, StatusCode, StreamExt, Terminal, Value, error, required_caps, @@ -35,7 +36,7 @@ async fn forward(g: Gateway, body: Bytes) -> Result { v["model"] = Value::String(d.model.clone()); let streaming = v.get("stream") == Some(&Value::Bool(true)); let deadline = - tokio::time::Instant::now() + Duration::from_millis(g.0.config.request_timeout_ms); + RuntimeClock.now() + Duration::from_millis(g.0.config.request_timeout_ms); let response = send_upstream(&g, worker, &v, deadline).await?; let code = response.status(); let is_sse = stream_kind(&response, code, streaming)?; diff --git a/desktop-core/src/pool.rs b/desktop-core/src/pool.rs index aba604cb..d97306d0 100644 --- a/desktop-core/src/pool.rs +++ b/desktop-core/src/pool.rs @@ -1,4 +1,5 @@ //! In-memory admission only: a lease covers the entire upstream request/stream. +use crate::clock::{Clock, RuntimeClock}; use serde::Serialize; use std::{ collections::{HashMap, VecDeque}, @@ -135,7 +136,7 @@ impl Pool { eligible: Vec, wait: Duration, ) -> Result { - let deadline = Instant::now() + let deadline = RuntimeClock.now() .checked_add(wait) .ok_or(AdmissionError::Invalid)?; let (tx, rx) = oneshot::channel(); @@ -195,7 +196,7 @@ impl State { let mut i = 0; while i < self.pending.len() { let p = &self.pending[i]; - if p.tx.is_closed() || p.deadline <= Instant::now() { + if p.tx.is_closed() || p.deadline <= RuntimeClock.now() { let p = self.pending.remove(i).unwrap(); let _ = p.tx.send(Err(AdmissionError::Expired)); continue; diff --git a/desktop-core/src/runtime_gateway/text_responses.rs b/desktop-core/src/runtime_gateway/text_responses.rs index af3d79c8..35156834 100644 --- a/desktop-core/src/runtime_gateway/text_responses.rs +++ b/desktop-core/src/runtime_gateway/text_responses.rs @@ -4,6 +4,7 @@ // The error value is the finished HTTP response: it is returned as it is, so it is large by design. #![allow(clippy::result_large_err)] +use crate::clock::{Clock, RuntimeClock}; use super::{ Body, Bytes, Duration, HeaderMap, IntoResponse, Json, Registry, Response, RuntimeClient, RuntimeGeneration, State, StatusCode, Trace, Value, error, json, proto, render, tool_responses, @@ -146,7 +147,7 @@ pub(super) async fn accepted( client: &mut RuntimeClient, request: proto::GenerateRequest, ) -> Result { - let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + let deadline = RuntimeClock.now() + Duration::from_secs(2); for attempt in 0..3 { let result = tokio::time::timeout_at(deadline, client.generate(request.clone())) .await diff --git a/docs/architecture/tech-debt.md b/docs/architecture/tech-debt.md index 5f81f2bd..125718ed 100644 --- a/docs/architecture/tech-debt.md +++ b/docs/architecture/tech-debt.md @@ -330,6 +330,11 @@ Left, with the reason: | `serving_cells()` (33 sites in 27 files) | the bound is an immutable process constant after start-up; the call sites are position and prompt-length checks on the decode and prefill paths | a `ServingBound` handle on the session and the request, with the identity gate | | 9 `dyn` of the hot path: `OriginalServePool` (host), `GdnGemm` (prefill batch), `Drain` (prefill profile) | per-round and per-layer calls; the change is semantics-neutral but touches the decode loop and the prefill ring | branch `claude/debt-hot-engine`, not merged before the laptop identity run | | `settings::process()` | leaf code that cannot take a parameter | S13/S14 | +| binary `leleka-api` | `leleka-api` | `control-plane/Cargo.toml` (`[[bin]]`, `default-run`), the usage texts, the service unit names (`leleka-api.service`, `leleka-api-NAME.service`), `leleka up`/`leleka run` calls (`leleka-api model ...`, `api-key init`), the installed file list and MANIFEST, `install.sh`, the Windows scripts (`leleka-api.exe`), the release and runtime-image build scripts, the CI workflows, the e2e harness scripts, the fake runtime double (`leleka-api` symlink) and the docs | +| crate `leleka-control-plane` | `leleka-control-plane` (identifier `leleka_control_plane`) | `Cargo.toml` of the workspace and of every dependent, `Cargo.lock`, `use` paths, `-p` arguments of scripts and CI, `architecture.json` and the baselines | +| crate `leleka-engine-host` | `leleka-engine-host` (identifier `leleka_engine_host`) | the same; the crate hosts the engine process `leleka-inference` (and `leleka-daemon`, `leleka-cli`, `leleka-seal-exec`) with the node, pool, managed worker and gateway services around it, so the name says what it hosts; the `strata-desktop` binary keeps its name (not part of the order) | + +Done by `scripts/dev/rename_strata_names.py` (a plain text replacement over the tracked files, rerunnable, which also catches what a branch merged later adds). `STRATA_*` environment variables stay. Not touched: `engine/strata` (the Original, including its Python package `strata_control`), `docs/experiments/` and `docs/e2e-data/` (records of what was run, with the names of that day), `docs/ledger*`, `docs/upstream/` and every `*.patch` (diffs against the Original). **Compatibility:** no `leleka-api` alias is shipped, because nothing outside the repository calls the binary by that name; a prefix installed by an older `leleka` is complete in itself (its `leleka`, its MANIFEST and its `leleka-api`), and a new `leleka up` takes the binaries from the package it was built in, which carries `leleka-api`; mixing a new `leleka` with an old package directory is not supported (the MANIFEST lists different files). The owner's running service (`leleka.service` on rnr5090) runs a package built before the rename and was not touched. ### (d) Other open items of this file (unchanged by the pass; the owner's order for them)